Formatting a column with EPPLUS Excel Library

elbillaf picture elbillaf · Feb 24, 2015 · Viewed 25.6k times · Source

I wrote a C# program to create an excel spreadsheet. The sheet has multiple columns. I want to format ONE of the columns.

aFile = new FileInfo(excelDocName); // excelDocName is a string
ExcelPackage pck = new ExcelPackage(aFile);
var ws = pck.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = true;
ws.Cells["B:B"].Style.Numberformat.Format = "0.00";
ws.Cells[1, 1].Value = "AA";
ws.Cells[1, 2].Value = "BB";
ws.Cells[1, 3].Value = "CC";
ws.Cells[1, 4].Value = "DD";
for (int row = 2; row <= 10; ++row)
  for (int col = 1; col <= 4; ++col)
  {
  ws.Cells[row, col].Value = row * col;
  }
ws.Row(1).Style.Font.Bold = true;
pck.Save();

The problem is, while it's formatting the column correct, it's also formatting other columns with the format and not just the column I specified. I also tried:

ws.Column(1).Style.Numberformat.Format = "0.00";

Is this a bug or am I missing something?

Answer

Ernie S picture Ernie S · Feb 24, 2015

Are you opening an existing file? It may have a format already applied to the other columns prior to you opening it. Or a template like astian said.

Clear all the formatting just in case like this:

ws.Cells["A:D"].Style.Numberformat.Format = null;
ws.Cells["B:B"].Style.Numberformat.Format = "0.00";

Full unit test in EPPlus 4.0.3:

[TestMethod]
public void Format_Single_Column_Test()
{
    //http://stackoverflow.com/questions/28698226/formatting-a-column-with-epplus-excel-library
    var excelDocName = @"c:\temp\temp.xlsx";
    var aFile = new FileInfo(excelDocName); // excelDocName is a string

    if (aFile.Exists)
        aFile.Delete();

    ExcelPackage pck = new ExcelPackage(aFile);
    var ws = pck.Workbook.Worksheets.Add("Content");
    ws.View.ShowGridLines = true;
    ws.Cells["A:D"].Style.Numberformat.Format = null;
    ws.Cells["B:B"].Style.Numberformat.Format = "0.00";
    ws.Cells[1, 1].Value = "AA";
    ws.Cells[1, 2].Value = "BB";
    ws.Cells[1, 3].Value = "CC";
    ws.Cells[1, 4].Value = "DD";
    for (int row = 2; row <= 10; ++row)
        for (int col = 1; col <= 4; ++col)
        {
            ws.Cells[row, col].Value = row*col;
        }
    ws.Row(1).Style.Font.Bold = true;
    pck.Save();
}