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



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

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

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

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

以上结果为空文档。如果我删除第二个身体。附录子行,然后它成功添加第一段。

请帮助我需要更改/添加什么。

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

System.InvalidOperationException - 无法插入 OpenXmlElement "newChild",因为它是树的一部分。

要解决此问题,您应该在每次需要时创建一个新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))

最新更新