Bookmark: HemiDemi MyShare Baidu Google Bookmarks Yahoo! My Web Del.icio.us Digg technorati furl Bookmark to:YouPush Bookmark to:你推我報

聖哥上課的時候,有學員問到能不能在伺服器端產生 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.ContentType = "application/pdf"
        Response.AddHeader("Content-disposition", "attachment; filename=Demo.pdf")
        Response.End()
    End Sub
End Class



代碼:
        ' 輸出 Excel
        Response.ContentType = "application/vnd.ms-excel"
        Response.AddHeader("Content-disposition", "attachment; filename=Demo.xls")
        Response.End()

Posted by romeogi1023 at 痞客邦 PIXNET Comments(0) Trackback(0) Hits(91)