문제

I'm looking for options to fill a Word Document from either Visual Basic, or Visual C#. I'm currently using merge fields, and the code below to fill specific fields in a Word Document, but now I've run into a situation where I need tabular data pushed to MS Word. Is there anyway to take data from a grid view (number of rows is dynamic), and import it into a Word Document Table using a merge field or something of that sort? I have to maintain the format of my template doc, and would like to be able to control the layout of the page ..

            Dim templateDoc As String = Server.MapPath("\Userfiles\docs\" & location)
            Dim mergePath As String = Server.MapPath("\App_Data\Temp\")
            Dim mergeFileName As String = location.Replace("/", "_") & ".docx"
            Dim mergeDoc As String = mergePath & "\" & mergeFileName

            File.Copy(templateDoc, mergeDoc, True)

            Using pkg As Package = Package.Open(mergeDoc, FileMode.Open, FileAccess.ReadWrite)

                Dim uri As Uri = New Uri("/word/document.xml", UriKind.Relative)
                Dim part As PackagePart = pkg.GetPart(uri)

                Dim xmlMainXMLDoc As XmlDocument = New XmlDocument()
                xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read))

                Dim innerXml As String = xmlMainXMLDoc.InnerXml _
                                         .Replace("«Corporate Legal Name»", businessName) _
                                         .Replace("«Address 1»", mailingAddress1) _
                                         .Replace("«Address 2»", mailingAddress2) _
                                         .Replace("«City»", city)
                xmlMainXMLDoc.InnerXml = innerXml

                Using partWriter As New StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write))
                    xmlMainXMLDoc.Save(partWriter)
                End Using

                pkg.Close()
            End Using
도움이 되었습니까?

해결책

Just like my answer for your question regarding Excel, Office writer will work for you here too!

다른 팁

You can write out in HTML and save it with a .doc extension and Word will handle it gracefully.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top