首页 > 解决方案 > 如何在 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
    }
}

标签: c#datacolumn

解决方案


在这里,我假设您的列已经添加。你可以试试这个。

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

推荐阅读