簡體   English   中英

使用OpenXML SDK 2.0從Excel單元讀取數據

[英]Reading data from Excel cells using OpenXML SDK 2.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查看和編輯的實數值。

有人猜為什么會這樣嗎?

每個Excel單元格中的值(大多數情況下)存儲在一個稱為SharedStringTable的公共位置。 該表就像一個數組,在其中添加每個唯一值,然后將其索引作為值放入實際的Excel單元格中。 這意味着您要檢索的4、5、248實際上是指向該表的實際索引,指向該單元格的實際值。 該表的重點是幫助減少存儲的冗余數據量。 例如,如果兩個單元格包含相同的字符串,則Excel僅需要將該字符串存儲在SharedStringTable一次,然后兩次將相同的字符串作為該單元格的值進行引用。 這將有助於減小文件的整體大小,因為您不需要在構成Excel文件的實際XML中存儲太多文本。

例如,我在單元格A1和A2中添加了文本“測試”,在單元格A3中添加了文本“唯一”,這就是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>

注意測試僅存儲一次。 這是單元格值:

<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都指向SharedStringTable的相同文本,因此它們的值均為0。

通過索引訪問SharedStringTable的簡單代碼段是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM