OpenXml SDK word 文档更改不可见

时间:2021-04-30 10:16:00

标签: vb.net ms-word openxml-sdk

我正在尝试读取内存中现有的单词模板文件,进行操作,最后刷新响应用户。我的模板有 2 组更改需要处理:

  1. 替换模板中的文本。
  2. 使用替换文本在文档中的特定位置插入表格。

两者单独工作都很好,但不能一起工作。我的代码可能有什么问题?

Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnPrint.Click
     Using ms As MemoryStream = Export()
         Dim bytes As Byte() = ms.ToArray()
         Response.Clear()
         Response.ClearHeaders()
         Response.Buffer = True
         Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
         Response.AddHeader("content-disposition", "attachment;filename=Proposal.docx")
         'Response.ContentType = "application/pdf"
         'Response.AddHeader("content-disposition", "attachment;filename=Proposal.pdf")
         Response.Headers.Add("content-length", bytes.Length.ToString())
         'Response.AddHeader("content-disposition", "attachment;filename=Proposal.docx")
         Response.OutputStream.Write(bytes, 0, bytes.Length)
         Response.Flush()
         Response.[End]()
     End Using
 End Sub

 Public Function Export() As MemoryStream
     Dim filepath As String = Server.MapPath("~/upload/PropertyBindingAuthorityProposalHC_1.docx")
     Dim byteArray As Byte() = File.ReadAllBytes(filepath)

     Using mem As MemoryStream = New MemoryStream()
         mem.Write(byteArray, 0, System.Convert.ToInt32(byteArray.Length))

         Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(mem, True)
             Dim docText As String = Nothing

             Using sr As StreamReader = New StreamReader(wordDoc.MainDocumentPart.GetStream())
                 docText = sr.ReadToEnd()
             End Using

             Dim objMdlProposal As MdlProposal = BllQuoteA.GetProposalData(hdnQteAId.Value.GetInteger())


             ' Create an empty table.
             table = New Wordprocessing.Table()

             For Each subj As MdlSubjectTo In objMdlProposal.Subjectivities
                 ' Create a row.
                 Dim tr As New Wordprocessing.TableRow()

                 ' Create a cell.
                 Dim tc1 As New Wordprocessing.TableCell()

                 ' Specify the width property of the table cell.
                 tc1.Append(New Wordprocessing.TableCellProperties(New Wordprocessing.TableCellWidth() With {.Type = Wordprocessing.TableWidthUnitValues.Pct, .Width = "100"}))

                 ' Specify the table cell content.
                 Dim runProperties1 As New Wordprocessing.RunProperties
                 Dim fontSize1 As New Wordprocessing.FontSize() With {.Val = "17"}
                 Dim fontFamily1 As New Wordprocessing.RunFonts() With {.Ascii = "Gadugi"}
                 runProperties1.Append(fontSize1)
                 runProperties1.Append(fontFamily1)


                 Dim run As New Wordprocessing.Run(New Wordprocessing.Text(subj.SubjDesc))
                 run.PrependChild(runProperties1)
                 tc1.Append(New Wordprocessing.Paragraph(run))

                 ' Append the table cell to the table row.
                 tr.Append(tc1)

                 table.Append(tr)
             Next

             tablePl = wordDoc.MainDocumentPart.Document.Body.Descendants(Of Wordprocessing.Text)().Where(Function(x) x.Text.Contains("QuoteSubjectives")).First()

             If tablePl IsNot Nothing Then
                 Dim parent As DocumentFormat.OpenXml.OpenXmlElement = tablePl.Parent.Parent.Parent
                 parent.InsertAfter(table, tablePl.Parent.Parent)
                 tablePl.Text = tablePl.Text.Replace("QuoteSubjectives", "")
                 wordDoc.MainDocumentPart.Document.Save()
             End If


             Using sr As StreamReader = New StreamReader(wordDoc.MainDocumentPart.GetStream())
                 docText = sr.ReadToEnd()
             End Using

             docText = New Regex("CoName").Replace(docText, objMdlProposal.CoName)
             docText = New Regex("BroName").Replace(docText, objMdlProposal.BroName)
             docText = New Regex("ConName").Replace(docText, objMdlProposal.ConName)
             docText = New Regex("BroMAddr1").Replace(docText, objMdlProposal.BroMAddr1)
             docText = New Regex("BroMAddr2").Replace(docText, objMdlProposal.BroMAddr2)
             docText = New Regex("BroMAddr3").Replace(docText, objMdlProposal.BroMAddr3)


             For Each header As HeaderPart In wordDoc.MainDocumentPart.HeaderParts
                 For Each currentText As Wordprocessing.Text In header.RootElement.Descendants(Of Wordprocessing.Text)()

                     If (currentText.Text.Contains("CoName")) Then
                         currentText.Text = currentText.Text.Replace("CoName", objMdlProposal.CoName.ToString())
                     End If

                 Next
             Next
                          
             'I can do quick watch here on docText and see all changes, but I get the document, all changes are not there (missing text replacement). If I turn off table insert code, the text replacement works.
             Dim bytes As Byte() = Encoding.UTF8.GetBytes(docText)
             Dim stream As MemoryStream = New MemoryStream(bytes)
             wordDoc.MainDocumentPart.FeedData(stream)

         End Using

         mem.Seek(0, SeekOrigin.Begin)
         Return mem
     End Using
 End Function

当调试时实际字符串发生变化时,我似乎无法弄清楚为什么我的更改在下载的文件中不可见。我可以在 docText 上的代码中快速查看,然后再将其反馈给 word 文档以在函数结束时作为内存流返回并查看所有更改,但在下载的文档中,所有更改都不存在(缺少文本替换) .如果我关闭表格插入代码,文本替换会起作用,但不能同时进行。

任何帮助将不胜感激。

0 个答案:

没有答案
相关问题