从C#中的数据表获取单元格值
问题描述:
这是一个具有大量数据的 DataTable dt 。
Here is a DataTable dt, which has lots of data.
我想从DataTable中获取具体的单元格值,例如 Cell [i,j] 。其中,
i - >行和j - >列。我将用两个 forloops
来迭代i,j的值。
I want to get the specific Cell Value from the DataTable, say Cell[i,j]. Where,
i -> Rows and j -> Columns. I will iterate i,j's value with two forloops
.
但是我无法弄清楚我可以如何调用一个单元格的索引。
But I can't figure out how I can call a cell by its index.
这里是代码:
for (i = 0; i <= dt.Rows.Count - 1; i++)
{
for (j = 0; j <= dt.Columns.Count - 1; j++)
{
var cell = dt.Rows[i][j];
xlWorkSheet.Cells[i + 1, j + 1] = cell;
}
}
答
DataRow
还有一个 indexer :
Object cellValue = dt.Rows[i][j];
But i would prefer the strongly typed Field
extension method which also supports nullable types:
int number = dt.Rows[i].Field<int>(j);
甚至更易于阅读,更少的错误容易出现列的名称:
or even more readable and less error-prone with the name of the column:
double otherNumber = dt.Rows[i].Field<double>("DoubleColumn");