【发布时间】:2016-07-06 03:07:44
【问题描述】:
任务
从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的替代品。
非常感谢您的建议
PS:我也想过通过使用像 A1, A2 这样的列名来获取单元格的值,但为了做到这一点,我必须获得列和行的确切计数,这不是可以通过使用Descendants 函数来实现。
【问题讨论】:
-
空单元格没有 e
Cell元素,因此您找不到它们。 -
@AlexanderDerck 那么如何解决这个问题呢?
-
使用 EPPlus 库会更容易(它使用 open xml sdk),参见示例here
-
您还可以要求单元格始终包含一个值。如果没有标记,则默认值为零。
标签: c# datatable openxml openxml-sdk spreadsheetml