2

LumenWorks有两个小问题CsvReader

第一个我的*.csv文件有一个;分隔符。没什么大不了的,我只需要更改阅读器中的分隔符属性,但实际上比这更棘手,因为标题;也以 a 结尾,但不是行。

例如 :

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 中的值?

谢谢

4

3 回答 3

2

依赖aCSVReader并不是一件坏事,但是如果您有特殊要求,也许依赖常规会更容易,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
于 2013-07-27T12:56:48.517 回答
1

要回答“第二个问题”如何选择列的子集:

Dim result As IEnumerable(Of String()) = csvCopy.
    Select(Function(fields) fields.Where(Function(f, i) column2Import.Contains(i))
                                  .ToArray()) 
于 2013-07-27T13:01:39.107 回答
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解决了我的第二个问题,其余的解决了我的第一个问题

于 2013-07-28T21:59:54.453 回答