如何在 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
    }
}

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

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

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

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

既然你不能使用 linq,那么这里是我们另一个解决方案

首先,您必须拥有 excel 中的行列表。 因此,您要做的第一件事是生成列,这是Excel文件中的第一行

var rowIndex =0;
forech (var row in excelrows){
DataRow dtRow= null;
var cellIndex = 0;
foreach (ExcelReportCell cell in row){
if (rowIndex ==0) // generate the columns
{
dt.Columns.Add(new ColumnData(cell.GetText().ToString()));
}else { // the columns has already been generated then generate the row
 dtRow = dtRow?? dt.NewRow();
 dtRow[cellIndex] = cell.GetText(); 
 }
cellIndex++;
}
if (dtRow != null)
  dt.Rows.Add(dtRow);
rowIndex ++;
}

相关内容

  • 没有找到相关文章

最新更新