open xml excel read cell value

后端 未结 5 1739
感动是毒
感动是毒 2020-11-27 05:24

I am using the Open XML SDK to open an Excel xlsx file and I try to read the cellvalue on position A1 in each sheet. I use the following code:

using (Spreads         


        
5条回答
  •  攒了一身酷
    2020-11-27 05:55

    All strings in an Excel worksheet are stored in a array like structure called the SharedStringTable. The goal of this table is to centralize all strings in an index based array and then if that string is used multiple times in the document to just reference the index in this array. That being said, the 0 you received when you got the text value of the A1 cell is the index into the SharedStringTable. To get the real value you can use this helper function:

    public static SharedStringItem GetSharedStringItemById(WorkbookPart workbookPart, int id)
    {
        return workbookPart.SharedStringTablePart.SharedStringTable.Elements().ElementAt(id);
    }
    

    Then in your code call it like this to get the real value:

    Cell cell = GetCell(worksheet, "A", 1);
    
    string cellValue = string.Empty;
    
    if (cell.DataType != null)
    {
        if (cell.DataType == CellValues.SharedString)
        {
           int id = -1;
    
           if (Int32.TryParse(cell.InnerText, out id))
           {
               SharedStringItem item = GetSharedStringItemById(workbookPart, id);
    
               if (item.Text != null)
               {
                   cellValue = item.Text.Text;
               }
               else if (item.InnerText != null)
               {
                   cellValue = item.InnerText;
               }
               else if (item.InnerXml != null)
               {
                   cellValue = item.InnerXml;
               }
           }
        }
    }
    

提交回复
热议问题