1

嗨,我有分配了一些值的字符串和整数。现在我需要读取字符串和整数值并将它们分配给我使用 VB.Net 创建的数据表。

If dt.Rows.Count > 0 Then 
For n As Integer = 0 To dt.Rows.Count - 1 
EmployeeNo = (dt.Rows(n)(0)) 
EmpName = (dt.Rows(n)(1)).ToString 
Commission = CDbl(dt.Rows(n)(2)) 
'I need to read one by one and assign the [EmployeeNo,EmpName,Commission] 
'to the dataset DtEmployee in which Employee is the table and EmpNo, EmpName, Commission 'are the coloumns.. 
Next 
End If 

请帮我解决这个问题..

4

1 回答 1

2

试试这个将整个工作表转储到 DataTable:

var connectionString = " Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";"
        var sheetName = "Sheet1";

        using (var con = new OleDbConnection(connectionString))
        {
            con.Open();

            var table = new DataTable(sheetName);
            var query = "SELECT * FROM [" + sheetName + "]";
            OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
            adapter.Fill(table);
            return table;
        }

编辑:根据更新的问题

If dt.Rows.Count > 0 Then 
For n As Integer = 0 To dt.Rows.Count - 1 
EmployeeNo = (dt.Rows(n)(0)) 
EmpName = (dt.Rows(n)(1)).ToString 
Commission = CDbl(dt.Rows(n)(2)) 
'I need to read one by one and assign the [EmployeeNo,EmpName,Commission] 
'to the dataset DtEmployee in which Employee is the table and EmpNo, EmpName, Commission 'are the coloumns.. 

Dim dataRow As DataRow = DtEmployee.Tables("Employee").AsEnumerable().Where(Function(row) row.Field(Of String)("EmpNo") = EmployeeNo).SingleOrDefault()
If dataRow IsNot Nothing Then

//Set your DataRow
dataRow("EmpName") = EmpName 
dataRow("Commission ") = Commission
DtEmployee.AcceptChanges();
End If

Next 
End If 

从 DtEmployee 表中找到行并更新该行,或者如果您想添加新行则不要找到行,只需创建新行并设置值并添加到 DtEmployee

DataRow dataRow  = DtEmployee.Tables("Employee").NewRow()
//Set your DataRow
 dataRow("EmpName") = EmpName 
 dataRow("Commission ") = Commission
DtEmployee.Tables("Employee").Rows.Add(dataRow)

希望这有帮助..

于 2012-05-22T06:40:56.713 回答