简体   繁体   中英

OpenXML Excel column format?

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

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.

You can get the name of the column through the cell reference and then get all the cells which are in the same column. If the first cell of the column has a style, you can apply it to the current cell using theirs StyleIndex.

You can take a look at this page which explain how to get the column name based on the cell reference : http://msdn.microsoft.com/en-us/library/office/cc822064.aspx

Maybe there is a more direct way to do what you want but I don't know it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM