NPOI set cell style

Sentence

C # or VB.NET is welcome.

I have the following code to create an Excel file with NPOI. It works great. I need to apply cell style to those rows in 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?

+3
source share
1 answer

You need to declare a row and cell outside the sth loop as follows:

Dim dataCell As HSSFCell
Dim dataRow As HSSFRow

Then inside the loop, you assign the value and style to the cell separately as follows:

    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
+2
source

Source: https://habr.com/ru/post/1767098/


All Articles