NPOI set cell style

Narazana picture Narazana · Sep 29, 2010 · Viewed 19k times · Source

C# or VB.NET suggestion are welcome.

I have the following code to create Excel file with NPOI. It's working fine. I need to apply the cell style to those rows in the loops.

Dim hssfworkbook As New HSSFWorkbook()

    Dim sheetOne As HSSFSheet = hssfworkbook.CreateSheet("Sheet1")
    hssfworkbook.CreateSheet("Sheet2")
    hssfworkbook.CreateSheet("Sheet3")
    hssfworkbook.CreateSheet("Sheet4")

        Dim cellStyle As HSSFCellStyle = hssfworkbook.CreateCellStyle
    cellStyle.Alignment = HSSFCellStyle.ALIGN_CENTER

      For i = 0 To 9 Step 1
        'I want to add cell style to these cells
        sheetOne.CreateRow(i).CreateCell(1).SetCellValue(i)
        sheetOne.CreateRow(i).CreateCell(2).SetCellValue(i)
  Next

How can I apply cell style to those rows in the loop above?

Answer

Tola picture Tola · Sep 29, 2010

You need to declare Row and Cell outside of the loop sth like this:

Dim dataCell As HSSFCell
Dim dataRow As HSSFRow

Then inside the loop, you assign value and style to cell separately like this:

    dataRow = sheetOne.CreateRow(i)
    dataCell = dataRow.CreateCell(1)
    dataCell.SetCellValue(i)
    dataCell.CellStyle = cellStyle

    dataRow = sheetOne.CreateRow(i)
    dataCell = dataRow.CreateCell(2)
    dataCell.SetCellValue(i)
    dataCell.CellStyle = cellStyle