从 C# 中的数据表中获取单元格值 [英] Get Cell Value from a DataTable in C#

查看:22
本文介绍了从 C# 中的数据表中获取单元格值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个DataTable dt,里面有很多数据.

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

我想从数据表中获取特定的单元格值,比如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 还有一个 索引器:

Object cellValue = dt.Rows[i][j];

但我更喜欢强类型的 Field 扩展方法,它也支持 可空类型:

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");

这篇关于从 C# 中的数据表中获取单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆