create a spreadsheet and have cells with colored background using the NPOI library

1.2k Views Asked by At

I am trying to create an Excel spreadsheet from a vb.net application using the NPOI library. I am using the following code:

Imports NPOI.HSSF.UserModel
Imports NPOI.SS.UserModel
Imports NPOI.SS.Util
Imports NPOI.HSSF.Util
Imports NPOI.POIFS.FileSystem
Imports NPOI.HPSF
Imports NPOI.HSSF.Util.HSSFColor

'create a background color of red
Dim styleCellRedBackGround As HSSFCellStyle = workbook.CreateCellStyle()
styleCellRedBackGround.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.RED.index
Dim styleCellRedBackGroundFont = workbook.CreateFont()
styleCellRedBackGroundFont.FontName = "Red Background"
styleCellRedBackGround.SetFont(styleCellRedBackGroundFont)

row = sheet.CreateRow(2)
cell = row.CreateCell(0)
cell.CellStyle = styleCellRedBackGround
cell.SetCellValue("<<COMPETITIVE REBATES>>")

The spreadsheet gets created, but there is no red background for the cell. If I create a cell and specify the red background, but do not write anything to the cell, this seems to work. There seems to be limited documentation on how to do this. Any suggestions?

Thanks

2

There are 2 best solutions below

0
On

Please set styleCellRedBackGround.FillPattern = FillPattern.SOLID;

0
On

You may want to create a style in an existing spreadsheet, open it with NPOI and see how the CellStyle is defined. This way you start with what you want up front and can create the corresponding code from there.