openxmlopenxml-sdk

`GetPartsOfType<SharedStringTablePart>()` returns `null` even though the cell data type is `SharedString`


I am following the example here to read values from cells in an Excel file.

However, even though cell.DataType.Value == CellValues.SharedString), calling workbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault() returns null.


if (cell.DataType is not null)
{
    if (cell.DataType.Value == CellValues.SharedString)
    {
        var stringTable = worksheetPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
        if (stringTable is not null)
        {}
        else
        {
            throw new Exception("null");
        }
}

Solution

  • The shared string table lives in the workbook part, not the worksheet part. If you look at the sample provided in the documentation it says wbPart:

    // For shared strings, look up the value in the
    // shared strings table.
    var stringTable = wbPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();