在asp.net要產生excel可以用很方便的原件NPOI,
要怎麼使用這邊有個範例
要怎麼使用這邊有個範例
- 請先去NPOI Project下載最新的dll
- reference NPOI 並且import
Imports NPOI.HSSF.UserModel
Imports NPOI.SS.UserModel
Imports NPOI.SS.Util
Imports NPOI.HSSF.Util
Imports NPOI.POIFS.FileSystem
Imports NPOI.HPSF
- 建立excel的 workbook和第一個sheet
Dim workbook As New HSSFWorkbook()
Dim sheet As HSSFSheet = workbook.CreateSheet("Sheet")
- 開始寫入Row資料
Dim rowIndex As Integer = 0
Dim row As HSSFRow = sheet.CreateRow(rowIndex)
row.CreateCell(0).SetCellValue("Name")
row.CreateCell(1).SetCellValue("Phone")
row.CreateCell(2).SetCellValue("Addess")
row.CreateCell(3).SetCellValue("gender")
row.CreateCell(4).SetCellValue("Email")
rowIndex = +1
- 寫入檔案
Dim fileName As String = Server.MapPath(".") + "/test.xls"
Using fileData = New FileStream(fileName, FileMode.Create)
workbook.Write(fileData)
End Using
- 如果要讓使用者下載可以用下面的code
Using exportData = New MemoryStream()
workbook.Write(exportData)
Dim saveAsFileName As String = String.Format("test.xls", DateTime.Now).Replace("/", "-")
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", saveAsFileName))
Response.Clear()
Response.BinaryWrite(exportData.GetBuffer())
Response.[End]()
End Using
留言