vb.net 下的 CSV文件操作

常见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,操作完毕。



上一篇: PHP删除、复制、重命名文件
下一篇: 使用VB.net建立excel文件
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: vb.net
相关日志:
评论: 0 | 引用: 0 | 查看次数: 129
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭

 广告位

↑返回顶部↑