以下内容会有帮助吗?
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;
}
}
}
}
}
注意:没有错误绑定检查或无效检查。它旨在说明如何以最简单的最小方式获取共享字符串。
此外,共享字符串列表被假定为“简单”共享字符串,这意味着没有富文本。
逻辑是您将工作表中的共享字符串列表加载到您可以轻松操作的列表中。然后,当您遍历单元格时,如果您看到数据类型为 SharedString 的单元格,则可以再次检查列表。如果单元格的数据类型为数字,则照常进行。