使用OpenXML SDK以stringforms获取所有单元格值

我想用类似于SAX的方式使用OpenXML SDK v2.0读取Excel 2007+文档。 我正在使用这个博客作为一个粗略的指导: http : //blogs.msdn.com/b/brian_jones/archive/2010/05/27/parsing-and-reading-large-excel-files-with-the-open -xml-sdk.aspx

但是,在我的文档中,我有一个string和数字值的混合。 因此,string值被存储为SharedString,所以当为这样的单元格读取CellValue时,我得到一个数字,我已经读取的是索引(因此需要获取InnerText)。 这似乎增加了太多的复杂性。 对于我来说,有没有简单地把工作表中的所有单元格当作文本/string,并通过所有的单元格来获取值,类似于博客文章的例子?

谢谢

下面会有帮助吗?

List<string> listShared = new List<string>(); using (SpreadsheetDocument xl = SpreadsheetDocument.Open("YourFile.xlsx", false)) { SharedStringItem ssi; using (OpenXmlReader oxrShared = OpenXmlReader.Create(xl.WorkbookPart.SharedStringTablePart)) { while (oxrShared.Read()) { if (oxrShared.ElementType == typeof(SharedStringItem)) { ssi = (SharedStringItem)oxrShared.LoadCurrentElement(); // this assumes the shared string is a simple text format, instead of rich text. listShared.Add(ssi.Text.Text); } } } WorksheetPart wsp = xl.WorkbookPart.WorksheetParts.First(); Cell c; using (OpenXmlReader oxrCells = OpenXmlReader.Create(wsp)) { while (oxrCells.Read()) { if (oxrCells.ElementType == typeof(Cell)) { c = (Cell)oxrCells.LoadCurrentElement(); // c.CellReference holds a string such as "A1" if (c.DataType != null) { if (c.DataType == CellValues.SharedString) { // use whichever from-string-to-number conversion // you like. //listShared[Convert.ToInt32(c.CellValue.Text)]; } else if (c.DataType == CellValues.Number) { // "normal" value //c.CellValue.Text; } // there's also boolean, which you might be interested // as well as other types } else { // is by default a Number. Use this: //c.CellValue.Text; } } } } } 

注意:没有错误绑定检查或无效检查。 这是为了说明如何以最简单的方式获取共享string。

此外,共享string列表被假定为“简单”共享string,这意味着没有丰富的文本。

逻辑就是将工作表中的共享string列表加载到List中,您可以轻松地操作它们。 然后,在遍历单元格时,如果看到数据types为SharedString的单元格,则可以再次检查列表。 如果单元格的数据types为Number,那么就照常进行。