下面會有幫助嗎?
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,那麼就照常進行。
非常感謝。有什麼辦法可以獲取CellReference的列和行號(整數)?也許我需要去的DOM方法,所以我可以有一個索引的行和列... – 2013-02-21 14:33:46