2014年4月2日 星期三

ASP.NET 使用Open Xml SDK 輸出Word檔

參考1:[Office]使用 OpenXML SDK 建立 Word 文件檔
參考2:[Office開發系列] 使用 OpenXML 將資料庫中的資料整合到 Word 文件中,且不假手 Office 物件模型
參考3:【雛型】Docx套版列印功能試作
參考4:How to: Insert a picture into a word processing document (Open XML SDK)

前置作業:
1.必須先下載安裝 Open XML SDK (我是使用 Open XML SDK 2.5 for Microsoft Office )

此篇純粹記錄程式碼
功能說明:取得現有的word檔,並在Word檔中的Table插入資料及圖片。

現有的Word檔(檔案名稱 testDoc.docx),格式如下圖:

程式產生出的Word檔,如下圖:


Code:

Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing
Imports A = DocumentFormat.OpenXml.Drawing
Imports DW = DocumentFormat.OpenXml.Drawing.Wordprocessing
Imports PIC = DocumentFormat.OpenXml.Drawing.Pictures
'===============================================
Imports System.IO

Partial Class test_word
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

        End If
    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim str_path As String = "C:\Users\SchoolDev\Desktop\test.docx"
        Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(str_path, WordprocessingDocumentType.Document)
            Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()
            mainPart.Document = New Document()
            Dim body As Body = mainPart.Document.AppendChild(New Body())
            Dim par As Paragraph = body.AppendChild(New Paragraph())
            Dim run As Run = par.AppendChild(New Run())
            run.AppendChild(New Text("Hello,ASP.NET利用Open Xml Sdk產生Word檔"))
        End Using
    End Sub

    Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim fs As FileStream = ReadTemplateFile()
        Dim doc As WordprocessingDocument = WordprocessingDocument.Open(fs, True)

        Dim document As Document = doc.MainDocumentPart.Document
        Dim table As Table = document.Body.GetFirstChild(Of Table)()

        Dim lastRow As TableRow = table.GetFirstChild(Of TableRow)()
        For y1 As Integer = 0 To 3
            Dim newRow As TableRow = CreateItemRow(y1, 3, doc)
            table.InsertAfter(newRow, lastRow)
            lastRow = newRow
        Next

        doc.MainDocumentPart.Document.Save()
        doc.Close()
        fs.Close()
    End Sub
    Function ReadTemplateFile() As FileStream
        Dim newFileName As String = "C:\Users\SchoolDev\Desktop\" & "doc_" & DateTime.Now.ToString("yyyyMMddHHmmss") & ".docx"
        File.Copy(Server.MapPath("testDoc.docx"), newFileName)
        Return New FileStream(newFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
    End Function
    Function CreateItemRow(ByVal row_y As Integer, ByVal cell_x As Integer, ByVal word1 As WordprocessingDocument) As TableRow
        Dim tableRow1 As TableRow = New TableRow()
        For x1 As Integer = 0 To cell_x - 1
            Dim tableCell1 As TableCell = New TableCell()
            Dim par1 As Paragraph = New Paragraph()
            Dim run1 As Run = New Run()
            Dim text1 As Text = New Text()

            text1.Text = "name" & row_y & "-" & x1
            run1.Append(text1)

            Dim img1 As ImagePart = word1.MainDocumentPart.AddImagePart(ImagePartType.Png)
            Using imgstream As New FileStream(Server.MapPath("./images/Symbol.png"), FileMode.Open)
                img1.FeedData(imgstream)
            End Using
            'DW.Extent(){.Cx = 192000L, .Cy = 192000L} Cx調整寬度 Cy調整高度
            Dim relationshipId As String = word1.MainDocumentPart.GetIdOfPart(img1)
            Dim element = New Drawing( _
                              New DW.Inline( _
                              New DW.Extent() With {.Cx = 192000L, .Cy = 192000L}, _
                              New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _
                              New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _
                              New DW.NonVisualGraphicFrameDrawingProperties( _
                              New A.GraphicFrameLocks() With {.NoChangeAspect = True} _
                                  ), _
                              New A.Graphic(New A.GraphicData( _
                                            New PIC.Picture( _
                                                New PIC.NonVisualPictureProperties( _
                                                    New PIC.NonVisualDrawingProperties() With {.Id = 0UI, .Name = "Picture.png"}, _
                                                    New PIC.NonVisualPictureDrawingProperties() _
                                                    ), _
                                                New PIC.BlipFill( _
                                                    New A.Blip( _
                                                        New A.BlipExtensionList( _
                                                            New A.BlipExtension() With {.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"}) _
                                                        ) With {.Embed = relationshipId, .CompressionState = A.BlipCompressionValues.Print}, _
                                                    New A.Stretch( _
                                                        New A.FillRectangle() _
                                                        ) _
                                                    ), _
                                                New PIC.ShapeProperties( _
                                                    New A.Transform2D( _
                                                        New A.Offset() With {.X = 0L, .Y = 0L}, _
                                                        New A.Extents() With {.Cx = 792000L, .Cy = 792000L}), _
                                                    New A.PresetGeometry( _
                                                        New A.AdjustValueList() _
                                                        ) With {.Preset = A.ShapeTypeValues.Rectangle} _
                                                    ) _
                                                ) _
                                            ) With {.Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"} _
                                        ) _
                                    ) With {.DistanceFromTop = 0UI, _
                                            .DistanceFromBottom = 0UI, _
                                            .DistanceFromLeft = 0UI, _
                                            .DistanceFromRight = 0UI} _
                                )
            run1.Append(element)

            par1.Append(run1)

            tableCell1.Append(par1)
            tableRow1.Append(tableCell1)
        Next

        Return tableRow1
    End Function

End Class