1
我正在使用OpenXML將Excel導入到DataTable。我的第一行合併爲僅顯示標題信息,第二行是標題行。從excel文件填充DataTable時,我得到的數據不正確。 DataTable正確填充,直到出現空白單元格爲止。當存在空白單元格時,它們將移動到相鄰的數據呈現單元格。這是爲什麼發生?代碼中有什麼問題?您能否幫我使用OpenXML以正確的方式獲取數據。數據導入後,這是我的Excel文件和數據表。導入Excel到DataTable使用OpenXML獲取數據不正確
我的代碼示例如下:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace OpenXMLDemo
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
var data = p.ExtractExcel(@"C:\TempData\");
}
public System.Data.DataTable ExtractExcel(string fullPath)
{
var excelFileToImport = Directory.GetFiles(fullPath, "Data_Import.xlsx", SearchOption.AllDirectories);
//Create a new DataTable.
System.Data.DataTable dt = new System.Data.DataTable();
//Open the Excel file in Read Mode using OpenXML
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(excelFileToImport[0], false))
{
WorksheetPart titlesWorksheetPart = GetWorksheetPart(doc.WorkbookPart, "Titles");
Worksheet titlesWorksheet = titlesWorksheetPart.Worksheet;
//Fetch all the rows present in the worksheet
IEnumerable<Row> rows = titlesWorksheet.GetFirstChild<SheetData>().Descendants<Row>();
//Loop through the Worksheet rows
foreach (Row row in rows)
{
//Use the first row to add columns to DataTable.
if (row.RowIndex.Value == 1)
{
}
else if (row.RowIndex.Value == 2)
{
foreach (Cell cell in row.Descendants<Cell>())
{
dt.Columns.Add(GetValue(doc, cell));
}
}
else
{
//Add rows to DataTable.
dt.Rows.Add();
int i = 0;
foreach (Cell cell in row.Descendants<Cell>())
{
dt.Rows[dt.Rows.Count - 1][i] = GetValue(doc, cell);
i++;
}
}
}
}
return dt;
}
private string GetValue(SpreadsheetDocument doc, Cell cell)
{
string value = cell.CellValue.InnerText;
if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
{
return doc.WorkbookPart.SharedStringTablePart.SharedStringTable.ChildElements.GetItem(int.Parse(value)).InnerText;
}
return value;
}
public WorksheetPart GetWorksheetPart(WorkbookPart workbookPart, string sheetName)
{
string relId = workbookPart.Workbook.Descendants<Sheet>().First(s => sheetName.Equals(s.Name)).Id;
return (WorksheetPart)workbookPart.GetPartById(relId);
}
}
}
的可能重複:([C#OPEN XML而從EXCEL中獲取數據,以DATATABLE空單元越來越跳過] https://stackoverflow.com/questions/36100011/c-sharp-open-xml-empty-細胞正在越來越跳過,而數據從Excel裏跳過) – PaulF
空單元格沒有列出 - 所以你需要檢查CellReference來查看哪個列存儲單元格數據。上面的鏈接顯示瞭如何做做你想做的事。 – PaulF