vandana sharma
vandana sharma

Reputation: 191

NPOI set cell style "HSSFFont.BOLDWEIGHT_BOLD" is not working

I'm using NPOI to output excel from Asp.Net. I want to set bold and normal style to my cell but it is working for few cell and not for remaining cell.Please have look on following example:

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

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

    Dim font As HSSFFont = _hssfworkbook.CreateFont()
    font.Boldweight = HSSFFont.BOLDWEIGHT_BOLD
    cellStyle.SetFont(font)

    For i = 0 To 9 Step 1
        'I want to add cell style to these cells
        If i Mod 2 = 0 Then 
                Sheet1.CreateRow(i).CreateCell(1).SetCellValue(i)
                font.Boldweight = HSSFFont.BOLDWEIGHT_BOLD
                cellStyle.SetFont(font)
                Sheet1.GetRow(i).GetCell(1).CellStyle = cellStyle
        Else
                Sheet1.CreateRow(i).CreateCell(1).SetCellValue(i)
                font.Boldweight = HSSFFont.BOLDWEIGHT_NORMAL
                cellStyle.SetFont(font)
                Sheet1.GetRow(i).GetCell(1).CellStyle = cellStyle
        End If
   Next

Actually code is working fine but i don't know the particular situation from where and why its stops working for remaining few rows. Its not working properly for all cells and from that particular cell the bold and normal property stops working on whole sheet like sheet2 and sheet3.

Upvotes: 2

Views: 11784

Answers (1)

BengalTigger
BengalTigger

Reputation: 114

You have to use multiple styles because a change to a style affects everywhere that style is referenced in the sheet.

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

Dim BoldFont As HSSFFont = hssfworkbook.CreateFont()
    BoldFont.Boldweight = HSSFFont.BOLDWEIGHT_BOLD
Dim NormalFont As HSSFFont = hssfworkbook.CreateFont()
    NormalFont.Boldweight = HSSFFont.BOLDWEIGHT_NORMAL
Dim cellStyleBold As HSSFCellStyle = hssfworkbook.CreateCellStyle()
With cellStyleBold
    .setFont(BoldFont)
    .Alignment = HSSFCellStyle.ALIGN_CENTER
End With
Dim cellStyleNormal As HSSFCellStyle = hssfworkbook.CreateCellStyle()
With cellStyleNormal
    .setFont(NormalFont)
    .Alignment = HSSFCellStyle.ALIGN_CENTER
End With

For i - 0 To 9 Step 1
    If i Mod 2 = 0 Then 
        With Sheet1.CreateRow(i).CreateCell(1)
             .SetCellValue(i)
             .cellStyle = cellStyleBold
        End With
    Else
        With Sheet1.CreateRow(i).CreateCell(1)
            .SetCellValue(i)
            .cellStyle = cellStyleNormal
        End With
    End If
Next

Upvotes: 4

Related Questions