ASP.NET 產生 PDF 或 XPS 檔

以下 ASP.NET 程式碼可以在伺服器端使用 Excel 檔當樣版,
修改 Excel 檔儲存格內容,然後使用列印或另存的方式來產生 PDF 或 XPS 檔,
先決條件是伺服器端有安裝 Office 2007 (如果要另存 PDF, XPS),
以及安裝增益集: http://www.microsoft.com/downloads/details.aspx?displaylang=zh-tw&FamilyID=4d951911-3e7e-4ae6-b059-a2e79ed87041
不要忘記加入參考: Microsoft.Office.Tools.Excel

代碼:
Imports Microsoft.Office.Interop
Imports System.IO

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim oExcel As New Excel.Application
Dim oBooks As Excel.Workbooks, oBook As Excel.Workbook
Dim oSheets As Excel.Sheets, oSheet As Excel.Worksheet
Dim oCells As Excel.Range
Dim sFile As String, sTemplate As String

' Excel 檔路徑
sTemplate = Server.MapPath("Demo.xlsx")

' 副檔名可以改成 .xls, .xps, .pdf
sFile = Server.MapPath(Session.SessionID & ".pdf")

oExcel.Visible = False
oExcel.DisplayAlerts = False

oBooks = oExcel.Workbooks
oBooks.Open(sTemplate)
oBook = oBooks.Item(1)
oSheets = oBook.Worksheets
oSheet = CType(oSheets.Item(1), Excel.Worksheet)
oCells = oSheet.Cells

' 設定第 8 列第 3 欄的值
oCells(8, 3) = "Hello World"

' 方式#1: 列印出 .XPS 檔
oSheet.PrintOutEx(PrintToFile:=True, PrToFileName:=sFile, Copies:=1)

' 方式#2: 另存成 PDF 檔
oSheet.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, sFile)

' 方式#3: 另存成 XLS 檔
oSheet.SaveAs(sFile)

oBook.Close()

oExcel.Quit()

Dim fs As FileStream = File.OpenRead(sFile)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bw As BinaryWriter = New BinaryWriter(Response.OutputStream)

Dim buffer(1024) As Byte
Dim count As Integer = br.Read(buffer, 0, buffer.Length)
Do While count > 0
bw.Write(buffer, 0, count)
count = br.Read(buffer, 0, buffer.Length)
Loop
br.Close()
bw.Close()

File.Delete(sFile)

' 輸出 PDF
Response.C
Response.AddHeader("Content-disposition", "attachment; filename=Demo.pdf")
Response.End()
End Sub
End Class


代碼:
' 輸出 Excel
Response.C
Response.AddHeader("Content-disposition", "attachment; filename=Demo.xls")
Response.End()
本文章來自於神魂顛倒論壇 http://bbs.flash2u.com.tw
原文網址:http://bbs.flash2u.com.tw/dispbbs_58_85452_4.html

留言

這個網誌中的熱門文章

嘗試卸載資料庫時,發生資料庫正在使用的而無法卸載的可能解決方案

PMP常用的英文單字