Search code examples
c#excelopenxmlnumber-formatting

Problem with OpenXML Library in C#: Numbers Not Recognized in Excel File Creation


I'm trying to create an Excel file using C# and I'm using the OpenXML library for this purpose. However, I've encountered a problem where numbers are not being recognized in the number format, resulting in errors as shown in the image below.

enter image description here

I'm sharing the part where I add data to the cell below:

 // The text here actually contains a number, like this: "1"
 CellValue cellValue = new CellValue(text);
 cell.DataType = CellValues.Number;
 cell.CellValue = cellValue;

Solution

  • Use the correct type instead of text :

    cell.DataType = CellValues.Number;
    cell.CellValue = new CellValue(1);
    

    Numbers in Excel aren't just text with the Number style. They're stored as strongly-type values in the XML file itself, ensuring there's never any confusion between 3.21 and 3,21 due to localized parsing.

    The CellValue constructor accepts different value types, including int, DateTime, Decimal, Boolean etc