如何使用OpenXML格式SDK从电子表格读取数据?

我需要使用Open XML SDK 2.0从Excel 2007工作簿中的单个工作表中读取数据。 我花了很多时间去寻找这样做的基本指导原则,但是我只能在创build电子表格方面find帮助。

如何迭代工作表中的行,然后迭代每行中的单元格,使用此SDK?

我这样做的方式是与Linq。 从使用SDK到纯粹的Open XML(没有SDK)这个问题上有很多的例子。 看一眼:

  • Office Open XML格式:检索Excel 2007单元格值 (使用纯OpenXML,而不是SDK,但概念非常接近)
  • 在Excel 2007中使用LINQ查询表 (使用Open XML SDK,假设为ListObject)
  • 从SpreadsheetML读取数据 (可能是最好的“整体介绍”文章)

另一个答案更像是一个元回答。 我一直在努力,因为使用LINQ可以处理分离的文档部分。 下面的代码包含一个包装函数,用于从Cell获取值,parsing任何可能的string查找。

public void ExcelDocTest() { Debug.WriteLine("Running through sheet."); int rowsComplete = 0; using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(@"path\to\Spreadsheet.xlsx", false)) { WorkbookPart workBookPart = spreadsheetDocument.WorkbookPart; foreach (Sheet s in workBookPart.Workbook.Descendants<Sheet>()) { WorksheetPart wsPart = workBookPart.GetPartById(s.Id) as WorksheetPart; Debug.WriteLine("Worksheet {1}:{2} - id({0}) {3}", s.Id, s.SheetId, s.Name, wsPart == null ? "NOT FOUND!" : "found."); if (wsPart == null) { continue; } Row[] rows = wsPart.Worksheet.Descendants<Row>().ToArray(); //assumes the first row contains column names foreach (Row row in wsPart.Worksheet.Descendants<Row>()) { rowsComplete++; bool emptyRow = true; List<object> rowData = new List<object>(); string value; foreach (Cell c in row.Elements<Cell>()) { value = GetCellValue(c); emptyRow = emptyRow && string.IsNullOrWhiteSpace(value); rowData.Add(value); } Debug.WriteLine("Row {0}: {1}", row, emptyRow ? "EMPTY!" : string.Join(", ", rowData)); } } } Debug.WriteLine("Done, processed {0} rows.", rowsComplete); } public static string GetCellValue(Cell cell) { if (cell == null) return null; if (cell.DataType == null) return cell.InnerText; string value = cell.InnerText; switch (cell.DataType.Value) { case CellValues.SharedString: // For shared strings, look up the value in the shared strings table. // Get worksheet from cell OpenXmlElement parent = cell.Parent; while (parent.Parent != null && parent.Parent != parent && string.Compare(parent.LocalName, "worksheet", true) != 0) { parent = parent.Parent; } if (string.Compare(parent.LocalName, "worksheet", true) != 0) { throw new Exception("Unable to find parent worksheet."); } Worksheet ws = parent as Worksheet; SpreadsheetDocument ssDoc = ws.WorksheetPart.OpenXmlPackage as SpreadsheetDocument; SharedStringTablePart sstPart = ssDoc.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault(); // lookup value in shared string table if (sstPart != null && sstPart.SharedStringTable != null) { value = sstPart.SharedStringTable.ElementAt(int.Parse(value)).InnerText; } break; //this case within a case is copied from msdn. case CellValues.Boolean: switch (value) { case "0": value = "FALSE"; break; default: value = "TRUE"; break; } break; } return value; } 

编辑:谢谢@ Nitin-Jadhav纠正GetCellValue()。