0

我试图以这种方式从 Excel 单元格中获取价值:

    SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(filePath, true);

    WorksheetPart worksheetPart = getWorksheetByName(spreadSheetDocument, DEFAULT_SHEET_NAME);

    SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

    Cell theCell1 = worksheetPart.Worksheet.Descendants<Cell>().FirstOrDefault(c => c.CellReference == "A5");
    Cell theCell2 = worksheetPart.Worksheet.Descendants<Cell>().FirstOrDefault(c => c.CellReference == "A6");
    Cell theCell3 = worksheetPart.Worksheet.Descendants<Cell>().FirstOrDefault(c => c.CellReference == "B5");
    Cell theCell4 = worksheetPart.Worksheet.Descendants<Cell>().FirstOrDefault(c => c.CellReference == "B6");

然后我正在检查 Cell1.CellValue.Text 属性,我得到了一些奇怪的数据,比如 4,5,248 等,这实际上与真实数据相去甚远。我可以使用 Excel 查看和编辑的实际值。

有谁知道为什么会这样?

4

1 回答 1

4

每个 Excel 单元格中的值(大部分)都存储在一个名为SharedStringTable. 该表就像一个数组,其中添加了每个唯一值,然后将其索引作为实际 Excel 单元格中的值。这意味着您要检索的 4、5、248 实际上是该表中的索引,指向该单元格的实际值。此表的目的是帮助减少存储的冗余数据量。例如,如果两个单元格包含相同的字符串,Excel 只需将字符串存储一次,SharedStringTable然后引用相同的字符串两次作为单元格的值。这将有助于减小文件的整体大小,因为您不需要在构成 Excel 文件的实际 XML 中存储尽可能多的文本。

例如,我在单元格 A1 和 A2 中添加了文本“测试”,在单元格 A3 中添加了文本“唯一”,这就是SharedStringTableXML 的样子:

<x:sst count="3" uniqueCount="2" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <x:si>
    <x:t>test</x:t>
  </x:si>
  <x:si>
    <x:t>unique</x:t>
  </x:si>
</x:sst>

注意 test 只存储一次。这是单元格值:

<x:c r="A1" t="s">
    <x:v>0</x:v>
  </x:c>
  <x:c r="B1" t="s">
    <x:v>0</x:v>
  </x:c>
  <x:c r="C1" t="s">
    <x:v>1</x:v>
</x:c>

注意 A1 和 A2 的值都是 0,因为它们都指向SharedStringTable.

通过索引访问 SharedStringTable 的简单代码片段是:

workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(index);
于 2012-11-01T10:36:16.940 回答