我正在寻找从 Visual Basic 或 Visual C# 填充 Word 文档的选项。我目前正在使用合并字段和下面的代码来填充 Word 文档中的特定字段,但现在我遇到了需要将表格数据推送到 MS Word 的情况。无论如何从网格视图中获取数据(行数是动态的),并使用合并字段或类似的东西将其导入 Word 文档表?我必须维护我的模板文档的格式,并且希望能够控制页面的布局..
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