我与LumenWorks的CsvReader
有两个小问题。
我的*.csv
文件中的第一个文件具有;
分隔符。没什么大不了的,我只需更改阅读器中的分隔符属性,但它实际上比那更棘手,因为标题以;
结尾但不是行。
例如:
Column1;Column2;Column3;
1;Michael;Page
2;Michael;Jackson
...
有没有办法向读者表明?
第二个问题我如何动态选择要导入的列?
我的代码编写如下:
Public Sub ImportCSV2Data(ByVal filename As String, ByRef gridToShow As GridControl, ByVal column2Import() As Integer)
Dim csvCopy As CachedCsvReader = New CachedCsvReader(New StreamReader(filename), True, ";"c)
Dim processedCopy = csvCopy.Select(Function(showColumn) New With{.SAPNo = column(0),.CCode = column(2)})
gridToShow.DataSource = processedCopy
End Sub
但是如何使所选列依赖于column2Import中的值?
由于
答案 0 :(得分:1)
依赖CSVReader
并不是一件坏事,但如果您有特殊要求,也许依靠传统的StreamReader
更容易,而不是花时间进行必要的修改。示例代码:
Dim sr As System.IO.StreamReader = New System.IO.StreamReader("target CSV file path")
Dim line As String
'Adapt this code to retrieve the column names from the file itself or from other source
Dim getColumnNames As Boolean = True
Dim columnNames() As String = Nothing
Do
line = sr.ReadLine()
If (line IsNot Nothing) Then
if(line.Contains(";")) then
If (columnNames Is Nothing And getColumnNames) Then
columnNames = line.Split(";")
Else
Dim curRowVals() As String = line.Split(";")
'All the row values
End If
End If
End If
Loop Until line Is Nothing
答案 1 :(得分:1)
回答“第二个问题”如何选择列的子集:
Dim result As IEnumerable(Of String()) = csvCopy.
Select(Function(fields) fields.Where(Function(f, i) column2Import.Contains(i))
.ToArray())
答案 2 :(得分:0)
Dim csvCopy As CachedCsvReader = New CachedCsvReader(New StreamReader(filename), True, ";"c)
csvCopy.MissingFieldAction = MissingFieldAction.ReplaceByEmpty
Dim headers() As String = csvCopy.GetFieldHeaders
For Each column As Integer In column2Import
datatable.Columns.Add(headers(column))
Next
While csvCopy.ReadNextRecord()
Dim csvRow As DataRow = datatable.NewRow
Dim i As Integer = 0
For Each column As Integer In column2Import
csvRow(i) = csvCopy(column)
i += 1
Next
datatable.Rows.Add(csvRow)
End While
csvCopy.MissingFieldAction = MissingFieldAction.ReplaceByEmpty
解决了我的第二个问题,其余部分解决了我的第一个问题