C# – OpenXML Excel column format

cexcelopenxmlopenxml-sdk

I am exporting some data to Excel via a template with OpenXML using the OpenXML SDK 2.0. I can get everything to export to Excel just fine. However, the template has several sheets (all of them actually) that have background colors (styles) applied to the column but not the cell as Excel does not have a real reference to that cell yet.

I am filling in data rows with data on these sheets and the values set fine, but when I set them the formatting of the cell it goes back to default white background and no longer fits with the rest of the sheet.

How do I get the cell to inherit the style of the column that it's in? I thought about trying to look up the column and get it's style and set the cell style to that, but I can't figure out how to find a column by it's reference. I can iterate all columns in a sheet but they don't give me their reference…

Here is the snippet that actually inserts the cell into a row:

    Cell newCell = new Cell() { CellReference = cellReference };
    if (refCell == null)
    { row.Append(newCell); }
    else
    { row.InsertBefore(newCell, refCell); }

refCell is from previous code and is basically to make sure that cells are listed in proper order as Excel will pitch a fit if they aren't…

Then the part that sets the actual value is:

     c.CellValue = new CellValue(indx.ToString());
     c.DataType = new EnumValue<CellValues>(CellValues.SharedString);

indx is the index of the string in the shared string table.

Can anyone help?

Thanks

Best Answer

How exactly are you setting the value. Normally there shouldn't be any override of the style, but I haven't tested this myself (we don't use templates).

Anyway: for finding the column reference, you can use:

ExcelColumn columnReference = ExcelWorksheet.Column(columnIndex);

Edit: I'm using the EPPlus library (http://epplus.codeplex.com/) for this, by the way. In my opinion it's a very easy to use implementation. I thought that was the one you were using, but I might be wrong.

Related Topic