如何用OpenXML实现Word文本两端对齐并优化VB代码?
使用OpenXML实现Word文本格式(加粗+两端对齐)
你的代码核心问题是结构不符合OpenXML规范,且混淆了段落格式与字符格式的层级关系——两端对齐是段落级属性,并非字符属性,同时所有文本不能塞进同一个段落和Run中。以下是修正并优化后的实现方案:
修正后的VB代码
Dim WordDocumentPath As String = "C:\Text.docx" ' 创建Word文档实例 Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(WordDocumentPath, WordprocessingDocumentType.Document) ' 添加主文档部分 Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart() mainPart.Document = New Document() Dim body As Body = mainPart.Document.AppendChild(New Body()) ' 处理Text1:加粗段落 Dim para1 As Paragraph = body.AppendChild(New Paragraph()) Dim run1 As Run = para1.AppendChild(New Run()) run1.AppendChild(New RunProperties(New Bold())) run1.AppendChild(New Text("Automation code 83743 on 2022-08-04 @ 091433")) ' 处理Text2:加粗段落 Dim para2 As Paragraph = body.AppendChild(New Paragraph()) Dim run2 As Run = para2.AppendChild(New Run()) run2.AppendChild(New RunProperties(New Bold())) run2.AppendChild(New Text("The power of the three samples provides no significant changes during the last period of test")) ' 处理Text3:两端对齐段落(不加粗) Dim para3 As Paragraph = body.AppendChild(New Paragraph()) ' 配置段落两端对齐属性 Dim paraProps As ParagraphProperties = para3.AppendChild(New ParagraphProperties()) paraProps.AppendChild(New Justification() With {.Val = JustificationValues.Justified}) Dim run3 As Run = para3.AppendChild(New Run()) run3.AppendChild(New Text("Sample A=8458349mg/L, Sample B=849922mg/L,....Sample Z48=798993mg/L")) End Using
关键优化说明
- 独立段落管理:每个文本段对应单独的
Paragraph,确保段落格式与字符格式可以分别控制 - 段落格式设置:两端对齐通过
ParagraphProperties下的Justification节点实现,设置值为JustificationValues.Justified - 字符格式设置:加粗是
Run级属性,通过给目标Run添加RunProperties+Bold节点实现 - 规范节点结构:修正了原代码中把
Paragraph嵌套进Run的错误,严格遵循OpenXML层级(Body → Paragraph → Run → Text/RunProperties)
内容的提问来源于stack exchange,提问作者Cliff
相关产品推荐
相关产品推荐

