我是Open XML的新手。这是我迄今为止所取得的成就:
我试图添加两个不同字体大小和理由的段落。 这是我的代码:
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行,那么它会成功添加第一段。
请帮助我更改/添加更多内容。
答案 0 :(得分:1)
您正在尝试将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))