温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Empty rows are getting skipped while getting data from Excel to DataTable
c# datatable excel openxml worksheet

c# - 从Excel将数据获取到DataTable时将跳过空行

发布于 2020-04-08 09:51:56

任务

将数据从Excel导入到DataTable

问题

某些不包含任何数据的行将被跳过,并且该行中有数据的下一个行被用作空行的值

例如

在Excel中,当我使用openxml将excel转换为Datatable时,共有37行,它跳过了空行,只读取了29行

WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
Worksheet workSheet = worksheetPart.Worksheet;
SheetData sheetData = workSheet.GetFirstChild<SheetData>();
IEnumerable<Row> rows = sheetData.Descendants<Row>();
foreach (Row row in rows) //this will also include your header row...
{
    DataRow tempRow = dt.NewRow();
    int ko = row.Descendants<Cell>().Count();
    for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
    {
        tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
    }
    dt.Rows.Add(tempRow);
}

查看更多

提问者
rajadurai
被浏览
24
Thomas Barnekow 2020-02-03 23:16

如果您查看Excel工作表的Open XML标记,您会发现标记中甚至不存在空行。这意味着当您在foreach循环中读取行时,将跳过那些空的,不存在的行。

如果要在中显示那些空行DataTable,则必须读取每个现有行,并跟踪所看到的最后一个行号。如果当前行号和您看到的最后一个行号之间存在间隙,则需要填写该间隙,DataRowDataRow为当前行添加新实例之前添加空实例

更新2020-02-03

若要了解如何确定行号,应查看示例工作表的Open XML标记。例如,以下标记显示了精简的示例工作表,其中仅包含sheetData元素和许多row子元素。您将看到每个row元素(Row类的实例)都有一个名为r的属性)的属性,该RowIndex属性Row指定行索引。在此示例中,我们看到第2、3、5和8行,因此我们看到第4、6和7行丢失了。

<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <sheetData>
    <row r="2" spans="2:2" x14ac:dyDescent="0.25">
      <c r="B2">
        <v>2</v>
      </c>
    </row>
    <row r="3" spans="2:2" x14ac:dyDescent="0.25">
      <c r="B3">
        <v>3</v>
      </c>
    </row>
    <row r="5" spans="2:2" x14ac:dyDescent="0.25">
      <c r="B5">
        <v>5</v>
      </c>
    </row>
    <row r="8" spans="2:2" x14ac:dyDescent="0.25">
      <c r="B8">
        <v>8</v>
      </c>
    </row>
  </sheetData>
</worksheet>