NPOI 匯出 Excel 時,隔行就更換字體樣式與顏色

同事跟我說,匯出時,能不能隔行就換字體樣式與顏色
所以DEMO一下,程式很簡單,就不多作說明了


Imports System.IO
Imports NPOI.HSSF.UserModel
-------------------------------------------------------------------
        Dim MS As MemoryStream = New MemoryStream()
        Dim WB As New HSSFWorkbook()

        Dim BoldFont As HSSFFont = WB.CreateFont()
        With BoldFont
            .Color = NPOI.HSSF.Util.HSSFColor.BLUE.index2
            .FontName = HSSFFont.FONT_ARIAL
            .FontHeightInPoints = 14
            .Boldweight = NPOI.SS.UserModel.FontBoldWeight.BOLD
        End With
        Dim cellStyleBold As HSSFCellStyle = WB.CreateCellStyle()
        cellStyleBold.SetFont(BoldFont)

        Dim NormalFont As HSSFFont = WB.CreateFont()
        With NormalFont
            .Color = NPOI.HSSF.Util.HSSFColor.BLACK.index
            .FontName = HSSFFont.FONT_ARIAL
            .FontHeightInPoints = 14
            .Boldweight = NPOI.SS.UserModel.FontBoldWeight.NORMAL
        End With
        Dim cellStyleNormal As HSSFCellStyle = WB.CreateCellStyle()
        cellStyleNormal.SetFont(NormalFont)

        Dim mySheet As HSSFSheet = WB.CreateSheet("Sheet1")
        For i = 0 To 9 Step 1
            If i Mod 2 = 0 Then
                With mySheet.CreateRow(i).CreateCell(1)
                    .SetCellValue(i)
                    .CellStyle = cellStyleBold
                End With
            Else
                With mySheet.CreateRow(i).CreateCell(1)
                    .SetCellValue(i)
                    .CellStyle = cellStyleNormal
                End With
            End If
        Next

        WB.Write(MS)
        Response.AddHeader("Content-Disposition", String.Format("attachment; filename=myName.xls"))
        Response.BinaryWrite(MS.ToArray())

        WB = Nothing
        MS.Close()
        MS.Dispose()

沒有留言:

張貼留言