【发布时间】:2021-09-28 15:07:41
【问题描述】:
我正在循环我的表格数据并尝试将表格行放在 excel 文件中,但我需要获取每一行的索引才能在我的 excel 文件中创建行。
foreach (DataRow row in dt.Rows)
{
xlWorkSheet.Cells[2, 1] = row["Id"].ToString();
xlWorkSheet.Cells[2, 2] = row["ProductId"].ToString();
xlWorkSheet.Cells[2, 3] = row["OrderQuantity"].ToString();
xlWorkSheet.Cells[2, 4] = row["CustomerID"].ToString();
xlWorkSheet.Cells[2, 5] = row["OrderDate"].ToString();
xlWorkSheet.Cells[2, 6] = row["Tax"].ToString();
xlWorkSheet.Cells[2, 7] = row["Total"].ToString();
xlWorkSheet.Cells[2, 8] = row["Net"].ToString();
}
我所需要的只是将xlWorkSheet.Cells[2, 8] 中的2(excel 行号)替换为foreach index 数字,而不是静态row 2,它将是row 3, 4,5,6,...,具体取决于我有多少行数据库。
有什么建议吗?
【问题讨论】:
-
使用在循环外声明并在其中递增的局部变量,或切换到 for 循环 for(int i = 0; i
-
@T.Schwarz 对不起,我不明白!那么我如何获得我的
row["Id"]? -
你可以使用 LINQ:
foreach(var (row,index) in dt.Rows.Select((v,i) => (v,i))) -
int rowcount = 0; foreach(dt.Rows 中的 DataRow 行){ xlWorkSheet.Cells[rowcount, 1] = row["Id"].ToString(); ....... 行数++;}