-1

I created a row and cell like this =

Row Row1 = new Row() { RowIndex = 1 };

            Row1.AppendChild(new Cell()
            {
                CellReference = "A1",
                DataType = CellValues.String,
                CellValue = new CellValue("Color this")
            });

Can anyone please tell me how to color this particular cell using openXml in C#? I don't want to color all the cells, only this particular cell.

Found the SOLUTION = https://learn.microsoft.com/en-us/archive/blogs/chrisquon/stylizing-your-excel-worksheets-with-open-xml-2-0

Sahil Vig
  • 60
  • 1
  • 8
  • Here is what you do and implement [LINK](https://stackoverflow.com/questions/1012547/creating-excel-document-with-openxml-sdk-2-0). It contains how you can create Fonts, Fill, CellFormat etc. – Pashyant Srivastava May 26 '21 at 12:45

2 Answers2

0

You need to create a PatternFill for that and set its background- or foregroundcolor. Then you will need to create a CellFormat which refers to that PatternFill. Then you set the StyleIndex of your cell to that CellFormat-index.

Dealing with styles in OpenXML is a real pain. Unless you have really good reasons to stick with OpenXML, my advise would be to switch to something like ClosedXML.

StefanFFM
  • 1,526
  • 1
  • 14
  • 25
  • Thanks. I'm only supposed to use OpenXML. I've found the solution and added it in my question. Giving you an upvote though :) – Sahil Vig May 28 '21 at 07:24
0

In my case I need to fill a range of cells with gray color. The approach I used is as follows

Dim cellRange As ExcelRange = CType(CurrentWorkSheet.Cells(6, 2, 6, 8), ExcelRange)
     cellRange.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid
     cellRange.Style.Fill.BackgroundColor.SetColor(Color.DarkGray)

The first is for selecting a range of cells. Next set the pattern and set the background color. I am trying to fill column 6's 8 cells (starting from 2nd cell)with a Gray color.

Note: I am using OfficeOpenXML

Hope it helps someone at some time. Happy Coding

Thomas Raj
  • 366
  • 3
  • 12