无法在打开的 xml word 文档中添加两个段落

Unable to add two paragraphs in open xml word document

我是 Open 新手 XML。这是我到目前为止能够实现的目标:

  1. 创建 Word 文档
  2. 添加带有一些文本的段落
  3. 通过更改段落属性 的对齐方式对齐文本
  4. 更改字体大小和粗体 (on/off)

我正在尝试添加两个具有不同字体大小和对齐方式的段落。 这是我的代码:

Dim FontHeading As New DocumentFormat.OpenXml.Wordprocessing.FontSize
FontHeading.Val = New StringValue("28")

Dim FontSubHeading As New DocumentFormat.OpenXml.Wordprocessing.FontSize
FontSubHeading.Val = New StringValue("24")

Dim wordDocument As WordprocessingDocument = WordprocessingDocument.Create(Server.MapPath("/test.docx"), WordprocessingDocumentType.Document)
Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()
mainPart.Document = New Document()

Dim dbody As New Body

dbody.AppendChild(AddParagraph("PREM CORPORATE", FontHeading, FontBold, CenterJustification))
dbody.AppendChild(AddParagraph("Company Incorporation Documents", FontSubHeading, FontBold, CenterJustification))

mainPart.Document.AppendChild(dbody)
mainPart.Document.Save()
wordDocument.Close()

添加段落的函数:

Private Function AddParagraph(ByVal txt As String, ByVal fsize As DocumentFormat.OpenXml.Wordprocessing.FontSize, ByVal fbold As Bold, ByVal pjustification As Justification) As Paragraph

   Dim runProp As New RunProperties
   runProp.Append(fsize)
   runProp.Append(fbold)

   Dim run As New Run
   run.Append(runProp)
   run.Append(New Text(txt))

   Dim pp As New ParagraphProperties
   pp.Justification = pjustification

   Dim p As Paragraph = New Paragraph
   p.Append(pp)
   p.Append(run)

   Return p

End Function

上面的结果是一个空文档。 如果我删除第二个 dbody.AppendChild 行,那么它会成功添加第一段。

请帮助我需要什么change/add。

您正在尝试将 BoldJustification 对象的 相同实例 添加到不同的 Paragraphs。这是不允许的,应该会导致错误:

System.InvalidOperationException - Cannot insert the OpenXmlElement "newChild" because it is part of a tree.

要解决这个问题,您应该在每次需要时创建一个新的 Bold 和一个新的 Justification

在您的 AddParagraph 方法中,您可以使用 Boolean 来表示文本是否应为粗体,并使用 JustificationValues 来表示使用的理由,然后创建新实例每个按要求:

Private Function AddParagraph(txt As String, fsize As DocumentFormat.OpenXml.Wordprocessing.FontSize, bold As Boolean, pjustification As JustificationValues) As Paragraph
    Dim runProp As New RunProperties()
    runProp.Append(fsize)
    If bold Then
        runProp.Append(New Bold())
    End If

    Dim run As New Run()
    run.Append(runProp)
    run.Append(New Text(txt))

    Dim pp As New ParagraphProperties()
    pp.Justification = New Justification() With { _
        Key .Val = pjustification _
    }

    Dim p As New Paragraph()
    p.Append(pp)
    p.Append(run)

    Return p

End Function

您添加 Paragraphs 的调用将如下所示:

dbody.AppendChild(AddParagraph("PREM CORPORATE", FontHeading, True, JustificationValues.Center))
dbody.AppendChild(AddParagraph("Company Incorporation Documents", FontSubHeading, True, JustificationValues.Center))