我正在尝试通过将Excel数据提取到Datatable将Excel转换为CSV,然后将其导入CSV。但是我在构造CSV时用空格/空字符替换逗号。如果Excel数据字段包含逗号,如何包含逗号? 我不想用任何其他字符替换它/包括字段的双引号。
这是我的代码:
command = New OleDbCommand("SELECT * FROM [" + SheetName + "$]", connection)
command.CommandType = CommandType.Text
writer = New StreamWriter(targetFile)
dataAdapter = New OleDbDataAdapter(command)
Dim dataTable As System.Data.DataTable = New System.Data.DataTable()
dataAdapter.Fill(dataTable)
Dim columnString As StringBuilder = New StringBuilder()
Dim column As Integer
For column = 0 To dataTable.Columns.Count - 1
If column = dataTable.Columns.Count - 1 Then
columnString.Append(dataTable.Columns(column).ToString())
Else
columnString.Append(dataTable.Columns(column).ToString() + ",")
End If
Next
writer.WriteLine(columnString)
Dim row As Integer
Dim rowString As StringBuilder
For row = 0 To dataTable.Rows.Count - 1
rowString = New StringBuilder()
For column = 0 To dataTable.Columns.Count - 1
If column = dataTable.Columns.Count - 1 Then
rowString.Append(dataTable.Rows(row)(column).ToString().Replace(",", ""))
Else
rowString.Append(dataTable.Rows(row)(column).ToString().Replace(",", "") + ",")
End If
Next
writer.WriteLine(rowString)
Next
如果我需要将逗号分成csv到datatable中,如何将数据从CSV读取到Datatable。
这是我的代码:
Using sr As StreamReader = New StreamReader(sourceFileFullName)
While Not sr.EndOfStream
Dim line = sr.ReadLine()
If Not String.IsNullOrEmpty(line) Then
If Not RowCount = 0 Then
chunkRowCount = chunkRowCount + 1
'//var chunkDataTable = ; //Code for filling datatable or whatever
dt1.Rows.Add()
Dim i As Integer = 0
Dim Cell As String
For Each Cell In line.Split(",")
If (String.IsNullOrEmpty(Cell)) Then
dt1.Rows(dt1.Rows.Count - 1)(i) = DBNull.Value
i = i + 1
ElseIf Cell = "00.00.0000" Then
dt1.Rows(dt1.Rows.Count - 1)(i) = DBNull.Value
i = i + 1
Else
dt1.Rows(dt1.Rows.Count - 1)(i) = Cell
i = i + 1
End If
Next
End If
RowCount = RowCount + 1
If chunkRowCount = 100000 Then
chunkRowCount = 0
Yield dt1
dt1.Clear()
End If
End If
End While