如何在C#中使用OpenXml为Word段落指定文本设置加粗、下划线格式?
在C# OpenXml SDK中给段落部分文本设置不同格式
嘿,这事儿其实很简单!OpenXml SDK里的Word段落是由多个Run(文本块)组成的——每个Run可以独立设置格式,所以你只需要把不同格式的文本拆成单独的Run,给每个Run配上对应的格式属性就行。
咱们直接拿你要的效果来举例:假设你想要实现 The total amount of Bank DHL is 25012 according to result.(其中“The total amount of”加粗,“Bank DHL”加下划线,其余保持默认),对应的代码实现如下:
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; // 假设你已经创建好Word文档对象(比如通过WordprocessingDocument.Create) using (var document = WordprocessingDocument.Create("TargetDocument.docx", WordprocessingDocumentType.Document)) { // 添加文档主部件 var mainPart = document.AddMainDocumentPart(); mainPart.Document = new Document(); var body = mainPart.Document.AppendChild(new Body()); // 创建目标段落 var paragraph = body.AppendChild(new Paragraph()); // 1. 加粗文本的Run var boldRun = new Run(); var boldProps = new RunProperties(); boldProps.Append(new Bold()); // 添加加粗属性 boldRun.Append(boldProps); boldRun.Append(new Text("The total amount of ")); // 注意末尾空格,保证文本连贯 paragraph.Append(boldRun); // 2. 下划线文本的Run var underlineRun = new Run(); var underlineProps = new RunProperties(); underlineProps.Append(new Underline { Val = UnderlineValues.Single }); // 设置单下划线 underlineRun.Append(underlineProps); underlineRun.Append(new Text("Bank DHL")); paragraph.Append(underlineRun); // 3. 默认格式的文本Run(无需额外设置RunProperties) var defaultRun1 = new Run(new Text(" is ")); paragraph.Append(defaultRun1); var defaultRun2 = new Run(new Text("25012 according to result.")); paragraph.Append(defaultRun2); // 保存文档 mainPart.Document.Save(); }
关键说明:
- 每个
Run对应一段格式统一的文本,拆分时要注意文本的连贯性(比如不要漏掉空格) RunProperties是格式属性的容器,你可以在里面添加Bold、Italic、FontSize等各种格式元素- 如果某个
Run没有设置RunProperties,就会自动使用文档的默认格式
这样就能完美实现段落内部分文本不同格式的需求啦!
内容的提问来源于stack exchange,提问作者Umer Waheed
相关产品推荐
相关产品推荐

