使用NPOI创建Excel文件

    Public Sub BuildExcel()
        '写入内容到Excel 
        Dim hssfworkbook As HSSFWorkbook = WriteExcel()

        Dim destFileName As String = "D:\test.xls"

        Dim msfile As New MemoryStream()

        hssfworkbook.Write(msfile)
        System.IO.File.WriteAllBytes(destFileName, msfile.ToArray())
    End Sub

    Private Function WriteExcel() As HSSFWorkbook

        Dim hssfworkbook As New HSSFWorkbook()

        Dim excelSheet As HSSFSheet = hssfworkbook.CreateSheet("sheet1")

        Dim row0 As HSSFRow = excelSheet.CreateRow(0)
        Dim cell0 As HSSFCell = row0.CreateCell(0)
        cell0.SetCellValue("NUM")

        cell0.CellStyle = GetCellStyle(hssfworkbook, HSSFCellStyle.BORDER_THIN, HSSFCellStyle.BORDER_THIN, HSSFCellStyle.BORDER_THIN _
                                       , HSSFCellStyle.BORDER_THIN, HSSFColor.LIGHT_YELLOW.index, "#,##0")

        Dim i As Integer = 100, j As Integer = 1
        While i < 10000
            Dim row As HSSFRow = excelSheet.CreateRow(j)
            Dim cell As HSSFCell = row.CreateCell(0)
            cell.SetCellValue(i)
            cell.CellStyle = GetCellStyle(hssfworkbook, HSSFCellStyle.BORDER_THIN, HSSFCellStyle.BORDER_THIN, HSSFCellStyle.BORDER_THIN _
                                          , HSSFCellStyle.BORDER_THIN, HSSFColor.LIGHT_GREEN.index, "#,##0")
            i += 1
            j += 1
        End While

        Return hssfworkbook
    End Function

    Private Function GetCellStyle(ByVal hssfworkbook As HSSFWorkbook, ByVal borderLeft As Short, ByVal borderBottom As Short, _
                                  ByVal borderRight As Short, ByVal borderTop As Short, ByVal fillforgeroundColor As Short, _
                                  ByVal dataFormat As String) As HSSFCellStyle
        Dim styleInfo As HSSFCellStyle = hssfworkbook.CreateCellStyle()

        styleInfo.BorderLeft = borderLeft
        styleInfo.BorderBottom = borderBottom
        styleInfo.BorderRight = borderRight
        styleInfo.BorderTop = borderTop

        styleInfo.Alignment = HSSFCellStyle.ALIGN_CENTER
        styleInfo.VerticalAlignment = HSSFCellStyle.VERTICAL_CENTER

        styleInfo.FillForegroundColor = fillforgeroundColor
        '设置填充色 
        styleInfo.FillPattern = HSSFCellStyle.SOLID_FOREGROUND
        '设置填充色的时候必须设置这个 
        styleInfo.DataFormat = HSSFDataFormat.GetBuiltinFormat(dataFormat)
        ' 当前日期格式的需要以下这样设置 
        'HSSFDataFormat format = (HSSFDataFormat)hssfworkbook.CreateDataFormat(); 
        'styleInfo.DataFormat = format.GetFormat("yyyy年m月d日"); 

        Return styleInfo
    End Function

 

posted on 2014-02-26 10:58  icycore  阅读(569)  评论(0编辑  收藏  举报

导航