Vb.net存csv文件,文件被打开后,再用程序存储就会存存不进去

 我来答
xiangjuan314
2016-04-18 · TA获得超过3.3万个赞
知道大有可为答主
回答量:2.9万
采纳率:0%
帮助的人:2909万
展开全部
参考
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
  必要时可以进行特殊字符的过滤
  VB.NET操作CSV文件中特殊字符的过滤
  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导入到DataTable,当然还可以像上面一样使用文件流操作,但这里采用OLEDB类实现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 第一行当数据处理
  '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,VB.NET操作CSV文件完毕。
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式