使用OpenXML SDK将所有单元格值作为字符串获取

3
我希望使用OpenXML SDK v2.0以SAX方式读取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 然而,在我的文档中,我有一些字符串和数值。因此,字符串值被存储为SharedString,所以当读取这样一个单元格的CellValue时,我得到一个数字,这个数字是索引(需要获取InnerText)。这似乎增加了太多的复杂性。是否有任何方法可以简单地将工作表中的所有单元格视为文本/字符串,并以类似于博文示例的方式迭代所有单元格并抓取值?
谢谢
1个回答

11

以下内容是否有帮助?

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;
                }
            }
        }
    }
}

注意:没有错误边界检查或空值检查。它旨在说明如何以尽可能简单的方式访问共享字符串。

此外,假定共享字符串列表是“简单”的共享字符串,即没有富文本。

逻辑是将工作表中的共享字符串列表加载到可以轻松操作的列表中。然后,当您遍历单元格时,如果看到共享字符串数据类型的单元格,只需再次检查列表即可。如果单元格是数字数据类型,则按照通常的方式继续。


非常感谢。有没有办法获取CellReference的列号和行号(整数)?也许我需要采用DOM方法,这样我就可以在行和列上拥有索引... - Erich Peterson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接