Search code examples
c#excelexcel-interopcell-formatting

How to set displayed decimals upon creating Excel file?


I am using the Interop library to create an Excel file and to write a double values to it, for example '1234.5678'. A lot of those values have a high number of decimals and displaying those decreases the readability of them. Also I do not want to loose those decimal places, so rounding is no option.

Excel has a nice way of dealing with this, since it lets you control the number of shown decimals using the buttons 'Increase Decimal' and 'Decrease Decimal' under the Home tab.

What I need however, is a way to set the number of shown decimal places directly from my application, is there a way to do this?

I use the following code to create a the file.

Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;

object misValue = System.Reflection.Missing.Value;

Excel._Application xlApp = new Excel.Application();

xlWorkBook = xlApp.Workbooks.Add(misValue);

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = 1234.5678;

Solution

  • xlWorkSheet.Cells[1, 1].NumberFormat = "0.000";
    

    "0.000" would display a number with 3 decimal points.

    Full list of formats: MSDN