将数据从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);
}
foreach
循环中读取行时,将跳过那些空的,不存在的行。如果要在DataTable
中保留那些空行,则必须读取每个现有行,并跟踪所看到的最后一个行号。如果当前行号和您看到的最后一个行号之间存在间隙,则需要填写该间隙,在为当前行添加新的DataRow
之前添加空的DataRow
实例。
更新2020-02-03
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>