vb.net 下的 CSV文件操作

常见CSV文件的操作

从DataTable导入到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
End Function
 
 

 

 

下面是CSV导入到DataTable,当然还可以像上面一样使用文件流操作,但这里采用OLEDB类操作。

 

从DataTable导入到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 第一行當數據處理
'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
End Function

 

OK,操作完畢。

转载于:https://www.cnblogs.com/scorpioyyy/archive/2008/10/08/1306578.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值