如何在C#中向数据列动态添加(或)插入值? [英] How to dynamically add (or) insert values to data column in c#?

查看:640
本文介绍了如何在C#中向数据列动态添加(或)插入值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在逐个单元地迭代一个excel文件。每个文件都有其自己的列数。基于excel单元格计数,我们正在动态创建数据表的列。这部分工作正常。

I am iterating an excel file cell by cell. Each file has its own number of columns. Based on excel cell count, we are dynamically creating the columns to the data table. This part is working fine.

我将必须将每个单元格值插入数据列。

I will have to insert each cell value to the data column. How to dynamically add (or) insert values to data column in c#?

在一个假设中,excel文件有2行3列

In an assumption, excel file has 2 rows and 3 colums

FirstName LastName Location
---------------------------
Albert     B         Miami
Jackson    C         Tampa

我必须填充数据具有这些单元格值的表/数据列。 Foreach循环迭代工作正常,并获取每个单元格值。
我一直坚持将每个单元格值插入数据列/数据行。

I will have to populate the data table / data column with these cell values. Foreach loop iteration is working fine and picking up each cell value. I am stuck on inserting each cell value to the data column / data row.

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


推荐答案

您需要添加所有列(使您的方法独立于列名,因此无需硬编码字符串),然后添加所有相应的值。

You need to add all the columns (make your method independent of the column name, so no hard coded strings) and then add all the respective values.

DataTable dt = new DataTable();
List<string> colList = new List<string>();

// Loop through column collection 
// Add all your columns to data table first
foreach (ExcelReportColumn eachColumn in excelColumn)
{
    dt.Columns.Add(eachColumn, typeof(string));
    colList.Add(eachColumn);
}

DataRow newRow;
int currentCol = 0;
// Then add your data rows
foreach (ExcelReportCell excelCell in excelRow)
{
    newRow = dt.NewRow();
    // Magic Method: You need to know the column name for the the current cell
    string columnName = colList[currentCol]; 
    newRow[columnName] = excelCell;
    dt.Rows.Add(newRow);
    currentCol++;
}

这篇关于如何在C#中向数据列动态添加(或)插入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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