c# - 如何在 C# 中动态地向数据列添加(或)插入值?
问题描述
我正在逐个单元格地迭代一个excel文件。每个文件都有自己的列数。基于 excel 单元格计数,我们正在动态创建数据表的列。这部分工作正常。
我将不得不将每个单元格值插入数据列。如何在 C# 中动态地向数据列添加(或)插入值?
假设,excel文件有2行3列
FirstName LastName Location
---------------------------
Albert B Miami
Jackson C Tampa
我将不得不用这些单元格值填充数据表/数据列。Foreach 循环迭代工作正常并获取每个单元格值。我坚持将每个单元格值插入数据列/数据行。
int iCellCount = 3; // In this example, i am defining cell count = 3 as static value. In the real time, cell count is picked from the excel file.
var cellValue = string.Empty;
DataTable dt = new DataTable();
foreach (ExcelReportCell excelCell in excelRow) // Iterating the excel cell row by row in the Excel Sheet
{
cellValue = excelCell.GetText().ToString(); // cellValue is assigned dynamically through excel file cell by cell iteration logic
for (int i = 1; i <= iCellCount; i++)
{
dt.Columns.Add();
// Expected to assign each column values
}
}
解决方案
在这里,我假设您的列已经添加。你可以试试这个。
int iCellCount = 3; // In this example, i am defining cell count = 3 as static value. In the real time, cell count is picked from the excel file.
var cellValue = string.Empty;
DataTable dt = new DataTable();
DataRow row; //Create a DataRow
foreach (ExcelReportCell excelCell in excelRow) // Iterating the excel cell row by row in the Excel Sheet
{
cellValue = excelCell.GetText().ToString(); // cellValue is assigned dynamically through excel file cell by cell iteration logic
for (int i = 1; i <= iCellCount; i++)
{
row = dt.NewRow();
row["Your_Column_Name_Here"] = cellValue;
dt.Rows.Add(row);
}
}
推荐阅读
- c++ - Karatsuba 实现 C++
- javascript - 如何使用 vue.js 处理动态表单
- postgresql - postgres=# du 并显示所有文件
- javascript - 将值分配给二维数组 javascript (node.js) 的问题
- regex - 将 XPath 与 CSS 选择器区分开来(正则表达式?)
- javascript - 不允许页面太大或太小的分页算法
- javascript - 来自 withTransaction 回调的 Mongoose 返回值
- angular - 向 FCM 发送 POST 请求不接受 Angular 中的授权标头
- c# - 使用数组和 For 循环的斐波那契数列
- ios - 使用调度等待数据附加到数组?