使用OpenXML SDK 2.0从Excel单元格中读取数据

我想通过这种方式从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 propetry,我得到了一些奇怪的数据,例如4,5,248等,这实际上远不是真实的数据。 我可以使用Excel查看和编辑的实际值。

有没有人猜测为什么呢?

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

例如,我在单元格A1和A2中添加了文本“test”,在单元格A3中添加了文本“unique”,这就是SharedStringTable XML的样子:

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

注意testing只存储一次。 这里是单元格的值:

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

请注意,A1和A2的值都是0,因为它们都指向SharedStringTable的相同文本。

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

 workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(index);