2013-02-19 64 views
2

我想以類似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使用OpenXML SDK將所有單元格值作爲字符串獲取

但是,在我的文檔中,我有一個字符串和數字值的組合。因此,字符串值被存儲爲SharedString,所以當爲這樣的單元格讀取CellValue時,我得到一個數字數字,我已經讀取的是索引(因此需要獲取InnerText)。這似乎增加了太多的併發症。無論如何,我只是簡單地將工作表中的所有單元格視爲文本/字符串,然後遍歷所有獲取值的單元格,類似於博客帖子示例。

謝謝

回答

9

下面會有幫助嗎?

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

注意:沒有錯誤綁定檢查或無效檢查。它旨在說明如何以最簡單的方式獲取共享字符串。

此外,共享字符串列表被假定爲「簡單」共享字符串,這意味着沒有富文本。

邏輯是,您將工作表中的共享字符串列表加載到List中,您可以輕鬆操作。然後,在遍歷單元格時,如果看到數據類型爲SharedString的單元格,則可以再次檢查List。如果單元格的數據類型爲Number,那麼就照常進行。

+0

非常感謝。有什麼辦法可以獲取CellReference的列和行號(整數)?也許我需要去的DOM方法,所以我可以有一個索引的行和列... – 2013-02-21 14:33:46

相關問題