VB.NET操作CSV文件實(shí)際代碼編寫(xiě)
大家作為開(kāi)發(fā)領(lǐng)域中的一員,應(yīng)該不會(huì)不知道VB.NET這一微軟.NET系列的編程語(yǔ)言。它的出現(xiàn)為開(kāi)發(fā)人員帶來(lái)了方便的編程環(huán)境。下面我們將會(huì)為大家詳細(xì)介紹有關(guān)VB.NET操作CSV文件的一些操作技巧。#t#
從DataTable導(dǎo)入到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
必要時(shí)可以進(jìn)行特殊字符的過(guò)濾
VB.NET操作CSV文件中特殊字符的過(guò)濾
- 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
- resultresult = result.Replace
(strSpac(i), "")- End If
- Next
- Return result
- End Function
下面是從CSV導(dǎo)入到DataTable,當(dāng)然還可以像上面一樣使用文件流操作,但這里采用OLEDB類實(shí)現(xiàn)VB.NET操作CSV文件。
- 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 第一行當(dāng)數(shù)據(jù)處理
- 'HDR=YES(默認(rèn))第一行當(dāng)列處理
- 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
- End Function
OK,VB.NET操作CSV文件完畢。