任务
将数据从 excel
导入到 DataTable
中
问题
不包含任何数据的单元格会被跳过,接下来有数据的单元格会被用作空列的值。例如:
A1 是空的,A2 有一个值 Tom
,那么在导入数据时,A1
将获得 A2 的值,而 A2 仍然为空。
为了使其更加清晰,我在下面提供了一些屏幕截图
这是 excel 数据
代码
public class ImportExcelOpenXml
{
public static DataTable Fill_dataTable(string fileName)
{
DataTable dt = new DataTable();
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(fileName, false))
{
WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
Worksheet workSheet = worksheetPart.Worksheet;
SheetData sheetData = workSheet.GetFirstChild<SheetData>();
IEnumerable<Row> rows = sheetData.Descendants<Row>();
foreach (Cell cell in rows.ElementAt(0))
{
dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
}
foreach (Row row in rows) //this will also include your header row...
{
DataRow tempRow = dt.NewRow();
for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
{
tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
}
dt.Rows.Add(tempRow);
}
}
dt.Rows.RemoveAt(0); //...so i'm taking it out here.
return dt;
}
public static string GetCellValue(SpreadsheetDocument document, Cell cell)
{
SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
string value = cell.CellValue.InnerXml;
if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
{
return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
}
else
{
return value;
}
}
}
我的想法
我认为public IEnumerable<T> Descendants<T>() where T : OpenXmlElement;
存在一些问题。
如果我想使用Descendants
得到列数,该怎么办?
IEnumerable<Row> rows = sheetData.Descendants<<Row>();
int colCnt = rows.ElementAt(0).Count();
或者
如果我使用 Descendants
来获取行数
IEnumerable<Row> rows = sheetData.Descendants<<Row>();
int rowCnt = rows.Count();`
在这两种情况下,
Descendants
都会跳过空单元格。是否有
Descendants
的替代方法。非常感谢您的建议。
附言:我也考虑过使用列名(如A1,A2)获取单元格值,但为了做到这一点,我需要获取确切的列数和行数,这是不可能使用
Descendants
函数实现的。
Cell
元素,因此您无法找到它们。 - Alexander Derck