C# DataTable importRow() 到空表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10856532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:33:21  来源:igfitidea点击:

DataTable importRow() into empty table

c#.netdatatable

提问by Kevin Zhou

I've been trying to merge an excel document with many sheets into a Datatable so that I can display said sheet in my winform app.

我一直在尝试将一个包含许多工作表的 Excel 文档合并到一个数据表中,以便我可以在我的 winform 应用程序中显示该工作表。

From reading around, I figured that Datatable.import(DataRow row) is my best bet. Thus my code looks as follows:

通过阅读,我认为 Datatable.import(DataRow row) 是我最好的选择。因此我的代码如下所示:

DataTable returnSet = new DataTable();
foreach (DataTable datTab in ds.Tables) // ds is extracted excel sheets in a dataset
{
  foreach (DataRow datRow in datTab.Rows) 
  {
    if (datRow.IsNull(0)) //if empty first col go on to next sheet
    {
      break;
    }
    else
    {
      returnSet.ImportRow(datRow);
    }
  }
}

When debugging, it shows that datRow/datTab is what I expected it to be, however after each ImportRow, returnSet is still an empty 1x1 cell. Any insight as to what I am doing wrong / missing would be greatly appreciated.

调试时,它显示 datRow/datTab 是我所期望的,但是在每个 ImportRow 之后,returnSet 仍然是一个空的 1x1 单元格。任何关于我做错了什么/遗漏的见解将不胜感激。

采纳答案by Tim Schmelter

I assume the reason is because your DataTable currently has no schema. You can try to clone the original DataTable to create the same schema(DataColumns etc).

我认为原因是因为您的 DataTable 当前没有架构。您可以尝试克隆原始 DataTable 以创建相同的架构(DataColumns 等)。

foreach (DataTable datTab in ds.Tables) // ds is extracted excel sheets in a dataset
{
    DataTable tblClone = datTab.Clone();
    foreach (DataRow datRow in datTab.Rows) 
    {

        if (datRow.IsNull(0)) //if empty first col go on to next sheet
        {
            break;
        }
        else
        {
            tblClone.ImportRow(datRow);
        }
    }
}