简体   繁体   中英

Retrieving data from excel cell that is integer .xslx document in C# documentformat.openxml

Iterating over rows and cells in my spreadsheet document but unable to retrieve the value from a cell if it is a number (string works fine).

For example:

// ...

List<Row> rows = sheetData.Elements<Row>().Where(r => r.Elements<Cell>().Any(ce => ce.DataType != null)).ToList();
foreach (Row row in rows) {
  foreach (Cell cell in row.Elements<Cell>()) {
    int id = int32.Parse(cell.InnerText);
    var value = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(id);

    Console.WriteLine(value); // the cell data
    // cell data is a string = fine.
    // cell data is a number = returns cell data from row 1, cell 1.

  }
}

When a cell is a number and not a string the value is equal to the first cell of the spreadsheet (0, 0).

Am I missing something here in retrieving numbers from cells?

Code is quick and dirty, but works:

if (cell.DataType == CellValues.SharedString && cell.DataType != null) {
  value = workbookPart.SharedStringTablePart.SharedStringTable
    .Elements<SharedStringItem>()
    .ElementAt(Convert.ToInt32(cell.InnerText)).InnerText;
} else {
  value = cell.InnerText.Replace(".", string.Empty);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM