您好我已经编写了一些代码来打开包含字段的word文档,例如«Date»,我正在尝试用数据库中的数据替换字段。 我将数据作为变量存储在数据库中,然后打开一个单词应用程序和文档,然后使用嵌套的if语句在for a循环中查找并用相应的值替换文档中的每个字段。
编辑:字段都是合并域:{MERGEFIELD Fieldname}
我想下载文件后或提示用户保存在他们的机器上。
我是否有正确的替代品或有更好的方法。 感谢
'Code to open the word template for invoices and editing it.
Protected Sub MakeDoc(ByVal sender As Object, ByVal e As EventArgs) Handles InvoiceGenBtn.Click
Dim ItmList = SQLHelper.RowQuery("SELECT * FROM QoItemList WHERE Quote_ID = @Quote_ID",
New SqlParameter("Quote_ID", Request.QueryString("QuoteID")))
'Variables.
Dim Qty = ItmList("Item_Quant")
Dim IName = ItmList("Item_Name")
Dim UPrice = ItmList("Item_QValue")
Dim TPrice = ItmList("Quote_TCliCost")
Dim Id = EditQuoteID.Text
Dim Client As String = DdlClient.Text
Dim Staff As String = DdlStaff.Text
Dim Dates = RadSDate.SelectedDate
Dim Total = SellValueTxt.Text
Dim WordTemplate As New Microsoft.Office.Interop.Word.Application()
Dim DocTemplate As New Microsoft.Office.Interop.Word.Document()
'Open and Store Doc Template.
DocTemplate = WordTemplate.Documents.Add("~/WordTemplates/BlankQuote.doc")
WordTemplate.Visible = True
'Find and rewrite the document on fields.
For Each Field As Microsoft.Office.Interop.Word.Field In DocTemplate.Fields
If Field.Code.Text.Contains("Date") Then
Field.Select()
WordTemplate.Selection.TypeText(Dates)
ElseIf Field.Code.Text.Contains("ID") Then
Field.Select()
WordTemplate.Selection.TypeText(Id)
ElseIf Field.Code.Text.Contains("Staff") Then
Field.Select()
WordTemplate.Selection.TypeText(Staff)
ElseIf Field.Code.Text.Contains("Client") Then
Field.Select()
WordTemplate.Selection.TypeText(Client)
ElseIf Field.Code.Text.Contains("TValue") Then
Field.Select()
WordTemplate.Selection.TypeText(Total)
ElseIf Field.Code.Text.Contains("QTY") Then
Field.Select()
WordTemplate.Selection.TypeText(Qty)
ElseIf Field.Code.Text.Contains("IName") Then
Field.Select()
WordTemplate.Selection.TypeText(IName)
ElseIf Field.Code.Text.Contains("UPrice") Then
Field.Select()
WordTemplate.Selection.TypeText(UPrice)
ElseIf Field.Code.Text.Contains("TPrice") Then
Field.Select()
WordTemplate.Selection.TypeText(TPrice)
End If
Next
'Download the File
DocTemplate.Save()
DocTemplate.Close()
WordTemplate.Quit()
End Sub
结束班
答案 0 :(得分:0)
有很多方法可以解决这个问题。使用Selection
通常效率不高,即使文档不可见和/或ScreenUpdating设置为false。
以下建议(仅限代码段)适用于Range
对象。它将Range
设置为循环开头的字段,并在字符串中拾取字段的代码。不多次调用Field.Code.Text
会更有效率。在查找字段时,将删除该字段并将文本写入该范围(删除该字段不会使范围无效)。
Dim rngField as Word.Range = Nothing
Dim sFieldCode as String
For Each Field As Microsoft.Office.Interop.Word.Field In DocTemplate.Fields
rngField = Field.Result
sFieldCode = Field.Code.Text
If sFieldCode.Contains("Date") Then
Field.Delete()
rngField.Text = Dates
ElseIf sFieldCode.Contains("ID") Then
Field.Delete()
rngField.Text = Dates