Search code examples
c#excelcellopenxml

OpenXml and strange behavior


I have the following code:

            for (int r = 0; r < rows.Count(); r++)
            {
                var cells = rows[r].Elements<Cell>().ToList();
                for (int c = 0; c < cells.Count(); c++)
                {
                    SharedStringTablePart shareStringPart = spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
                    SharedStringItem[] items = shareStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
                    int v = int.Parse(cells[c].CellValue.Text);
                    text = items[v].InnerText;
                }

and the following excel file:

enter image description here

but this code is crashed with

I debug it and look at CellValue (my v variable) for every cell of row #2.

cell[0] = 33 (and it get correct value PQ-10387)

cell1 = 22

cell[2] = 198

but

cell[3] = 310 and this value is the same value of cell! What is wrong in my code?


Solution

  • Found, that when cell stores a number, then CellValue has value of cell and DataType is null, otherwise DataType has value and CellValue stores index. So, this code works fine:

                for (int r = 0; r < rows.Count(); r++)
                {
                    var cells = rows[r].Elements<Cell>().ToList();
                    for (int c = 0; c < cells.Count(); c++)
                    {
                        SharedStringTablePart shareStringPart = spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
                        SharedStringItem[] items = shareStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
                        if (cells[c].DataType != null)
                        {
                            if (cells[c].CellValue != null)
                            {
                                int v = int.Parse(cells[c].CellValue.Text);
                                text = items[v].InnerText;
                            }
                        }
                        else
                            text = cells[c].CellValue?.Text;