Search code examples
c#excelformatepplus

C# EPPlus OpenOfficeXml Formatting cells


I am using the EPPlus library to create an excel file. I have some columns displaying string values, but the values are being processed as numeric values of dates. I want to format the cell to take the value as string not as date.

For example:

Original value: 1171-2, 1.1, 1.2, 1.3
Excel value: -266229, 42736, 42767, 42795

I am using:

excelWorksheet.Cells[row, column].Style.Numberformat.Format = "@";

but it is not working.

How can I format the cell to display the original value.


Solution

  • The "@" format instructs Excel to treat the value as Text, not a number.

    Without seeing your code I don't have anything to go on as to why excel would be converting your values as you've shown, so here's a code sample for setting cell formats:

            using (var xlsx = File.Create("Text.xlsx"))
            using (var pkg = new ExcelPackage())
            {
                var ws = pkg.Workbook.Worksheets.Add("Sheet1");
                var r = 0;
                ws.Cells[++r, 1].Value = "Values";
                ws.Cells[++r, 1].Value = 1171.2;
                ws.Cells[++r, 1].Value = 1.1;
                ws.Cells[++r, 1].Value = 1.2;
                ws.Cells[++r, 1].Value = 1.3;
                ws.Column(1).Style.Numberformat.Format = "General"; // Default
                //ws.Column(1).Style.Numberformat.Format = "0.00";    // Numeric with fixed decimals
                //ws.Column(1).Style.Numberformat.Format = "@";       // Text
                pkg.SaveAs(xlsx);
            }