Search code examples
c#decimalexport-to-excelglobalizationseparator

Export double to Excel - decimal separator issue


I'm having problems when exporting data in double format to Excel using Microsoft.Office.Interop.Excel.

Numbers like

-49,65454324566 (using comma as decimal separator)

in the code are exported as

-4965454324566

without comma, dot or any decimal separator.

Only numbers like

0,988946533164

i.e., less than 1, are exported in the correct format.

I've tried using NumberFormat but I don't have any restrictions of number of integer or decimal carachters, that means, I want to have numbers like 123,456789 or 123456,789. So I don't know if NumberFormat fits my needs.

Just to show, I'm doing something like:

Excel.Range cel = (Excel.Range)excel.Cells[1, 1];
cel[r, c] = table.Rows[r][c];

I've also tried:

Excel.Range cel = (Excel.Range)excel.Cells[1, 1];
cel[r, c] = table.Rows[r][c];
cel[r, c].NumberFormat = "#,#";

and variations of NumberFormat as "0,0", "#0,#0"...


Solution

  • With comma as a decimal separator, you aren't using en-US Regional settings. You will need to check to make sure that Excel knows this, or convert the number into en-US settings before sending it to excel. There are functions inside the .ToString() overloads that you can use.

    i.ToString(new System.Globalization.CultureInfo("en-US").NumberFormat);