[VB.NET]用NPOI匯出excel檔案

[VB.NET]用NPOI匯出excel檔案

NPOI 1.2.4可在此下載http://npoi.codeplex.com/releases/view/56605

我是下載NPOI 1.2.4 assembly

NPOI 1.2.4 examples 也有許多的範例能看

這個範例我使用 NPOI 匯出九九乘法表的excel檔案

下載好就先參考進來,只有用到NPOI.dll

需要特別注意的是每一列跟每一欄都只能建立一次

CreateRow 是建立第幾列,然後要用CreateCell建立第幾行,之後再用SetCellValue 去設定內容

 

以下為完整的code

Imports NPOI.HSSF.UserModel
Imports System.IO 
Public Class Form1
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim workbook As HSSFWorkbook = New HSSFWorkbook()
        Dim sheet1 As HSSFSheet = workbook.CreateSheet("sheet1")
        Dim row As HSSFRow
        Dim cell As HSSFCell
        Dim rowIndex As Integer = 0
        While rowIndex < 9
            row = sheet1.CreateRow(rowIndex)
            Dim colIndex As Integer = 0
            While colIndex <= rowIndex
                cell = row.CreateCell(colIndex)
                cell.SetCellValue([String].Format("{0}*{1}={2}", rowIndex + 1, colIndex + 1, (rowIndex + 1) * (colIndex + 1)))
                System.Math.Max(System.Threading.Interlocked.Increment(colIndex), colIndex - 1)
            End While
            System.Math.Max(System.Threading.Interlocked.Increment(rowIndex), rowIndex - 1)
        End While
        Dim file As New FileStream(Path.Combine(Application.StartupPath, "test.xls"), FileMode.Create)
        workbook.Write(file)
        file.Close()
    End Sub
End Class

參考此篇文章

他的是c#語法,我改成vb.net語法

NPOI_sample.rar


如有錯誤 歡迎指正