vb.net 下的 CSV文件操作
作者:admin 日期:2022-05-03
常见CSV文件的操作
Private Function ExportCsvProcess(ByVal FilePath As String ByVal, dt As DataTable) As Boolean
Dim fileStream As System.IO.FileStream
Dim streamWriter As System.IO.StreamWriter
Dim intRow, intCol As Integer
Dim strRow As String
'删除旧CSV文件
If (System.IO.File.Exists(FilePath)) Then
System.IO.File.Delete(FilePath)
End If
Try
fileStream = New FileStream(FilePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)
If Not dt Is Nothing Then
streamWriter = New StreamWriter(fileStream, System.Text.Encoding.Default)
strRow = ""
'讀列名
For intCol = 0 To dt.Columns.Count - 1
strRow += dt.Columns(intCol).ColumnName
If intCol < dt.Columns.Count - 1 Then
strRow += ","
End If
Next
streamWriter.WriteLine(strRow)
'读每行的值
For intRow = 0 To dt.Rows.Count - 1
strRow = ""
For intCol = 0 To dt.Columns.Count - 1
strRow += CStr(dt.Rows(intRow).Item(intCol))
If intCol < dt.Columns.Count - 1 Then
strRow += ","
End If
Next
streamWriter.WriteLine(strRow)
Next
streamWriter.Close()
End If
Catch ex As Exception
MessageShow(ex.ToString())
Return False
Finally
fileStream.Close()
End Try
Return True
End Function
必要时可以进行特殊字符的过滤
Private Function DelSpacChr(ByVal str As String) As String
Dim i As Integer
Dim result As String = str
Dim strSpac() As String = {"~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?"}
For i = 0 To i < strSpac.Length
If result.IndexOf(strSpac(i)) > -1 Then
result = result.Replace(strSpac(i), "")
End If
Next
Return result
下面是从CSV导入到DataTable,当然还可以像上面一样使用文件流操作,但这里采用OLEDB类操作。
Public Function CSVToDataTable(ByVal FilePath As String) As DataTable
Try
If (System.IO.File.Exists(FilePath)) Then
Dim fi As New System.IO.FileInfo(FilePath)
'HDR=NO 第一行当数据处理
'HDR=YES(默认)第一行当列处理
Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Text;HDR=NO';Data Source=" & fi.DirectoryName
Dim objConn As New System.Data.OleDb.OleDbConnection(sConnectionString)
objConn.Open()
Dim strColum As String
Dim objCmdSelect As New Data.OleDb.OleDbCommand("Select Distinct * FROM " & fi.Name, objConn)
Dim objAdapter As New Data.OleDb.OleDbDataAdapter
Dim dt As New DataTable
objAdapter.SelectCommand = objCmdSelect
objAdapter.Fill(dt)
objConn.Close()
Return dt
End If
Catch ex As Exception
MessageShow(ex.ToString())
Return Nothing
End Try
OK,操作完毕。
广告位