我的VB.NET函数从Excel工作表中读取数据并在Datatable中添加行。
Private Function LoadDataToRows(ByVal TableName As DataTable, ByVal Header As System.Collections.Specialized.StringCollection) As Boolean
Dim HeaderDataExcel As String = String.Empty 'Data Header
For r As Integer = 1 To RangeDataArray.Rows.Count
Dim NewRow As DataRow = TableName.NewRow
For c As Integer = 1 To RangeDataArray.Columns.Count
If Not (IsNothing(DirectCast(ActiveSheetToManipulate.Cells.Item(r + DataStartRow, c), Excel.Range).Value)) Then
Dim ValueToLoad As String = TryCast(ActiveSheetToManipulate.Cells.Item(r + DataStartRow, c), Excel.Range).Value.ToString
HeaderDataExcel = TryCast(ActiveSheetToManipulate.Cells.Item(DataStartRow, c), Excel.Range).Value.ToString
Dim indice As Integer = Header.IndexOf(HeaderDataExcel)
TableName.NewRow(indice) = ValueToLoad
Else
'Todo
End If
Next
TableName.Rows.Add(NewRow)
Next
Return True
End Function
但没有数据添加到表中。有什么建议吗?
答案 0 :(得分:1)
我不是VB.NET程序员,但您可能需要更改DataTable参数以传递ByRef而不是ByVal
另外,填充NewRow列的语法是否正确?您应该使用创建的新数据行实例而不是使用TableName.NewRow?
我觉得它更像是:
Dim newRow As DataRow = TableName.NewRow()
newRow ("ColumnName") = "MyNewValue" ' Add specifying column name
newRow (2) = "AnotherValue" ' Add specifying column index
TableName.Rows.Add(newRow)
所以你的代码将类似于以下内容(注意我已经更改了新行变量的名称,因为我认为这会导致你的一部分混乱)
Dim rowToAdd As DataRow = TableName.NewRow()
For c As Integer = 1 To RangeDataArray.Columns.Count
If Not (IsNothing(DirectCast(ActiveSheetToManipulate.Cells.Item(r + DataStartRow, c), Excel.Range).Value)) Then
Dim ValueToLoad As String = TryCast(ActiveSheetToManipulate.Cells.Item(r + DataStartRow, c), Excel.Range).Value.ToString
HeaderDataExcel = TryCast(ActiveSheetToManipulate.Cells.Item(DataStartRow, c), Excel.Range).Value.ToString
Dim indice As Integer = Header.IndexOf(HeaderDataExcel)
rowToAdd(indice) = ValueToLoad
Else
'Todo
End If
Next
TableName.Rows.Add(rowToAdd)