Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Here is a DataTable dt, which has lots of data.

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.

Here's the code:

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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
514 views
Welcome To Ask or Share your Answers For Others

1 Answer

The DataRow has also an 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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...