終於有空可以來發文章了~
這次將接續上一篇NPOI的使用方法
再次附一下NPOI網址
進入正文
這裡將上篇不同的部分做示範
但這次匯出方式為另一種---->在Web上匯出強制下載
還不懂前面運作請至上一篇-->[ASP.NET]如何使用NPOI產出Excel表- 指定路徑篇
不同部分在於匯出的方式
'//新增儲存位置
Dim filePath As New FileStream(tmpPath &fileName , FileMode.Create)
workbook.Write(filePath)
'用完就隨手關
filePath.Close()
filePath = Nothing
workbook = Nothing
以上為上一篇匯出方式
這裡將用另一種方式來寫
'//設定網頁ContentType
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
'//檔案名稱
Dim fileName As String = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"
'//設定強制下載標頭
HttpContext.Current.Response.AddHeader("Content-Disposition"
, String.Format("attachment;filename={0}", fileName))
HttpContext.Current.Response.Clear()
'//產生 Excel 資料流
Dim ms As New MemoryStream()
'//報表寫入資料流'
workbook.Write(ms)
'//輸出檔案'
HttpContext.Current.Response.BinaryWrite(ms.GetBuffer())
'//釋放資源'
workbook = Nothing
ms.Close()
ms.Dispose()
HttpContext.Current.Response.End()
其實也就是將NPOI產出的資料寫進網頁的資料流裡面供前端下載檔案~
希望能對各位有所幫助!!
若有錯誤或問題歡迎留言
下次見囉~
