我使用下面的代码将两种不同的字符样式应用于一个段落的两次运行:
Paragraph heading = new Paragraph();
ParagraphProperties heading_pPr = new ParagraphProperties();
heading.Append(heading_pPr);
Run Run1 = new Run() { RsidRunProperties = "009531B2" };
Text Text_Run1 = new Text("THIS IS TEST RUN 1");
Run1.Append(Text_Run1);
RunProperties rpr_Run1 = new RunProperties();
rpr_Run1.RunStyle = new RunStyle() { Val = "CharacterStyle1" };
Run Run2 = new Run();
RunProperties rpr_Run2 = new RunProperties();
rpr_Run2.RunStyle = new RunStyle() { Val = "CharacterStyle2" };
Text text_Run2 = new Text("THIS IS TEST RUN 2");
Run2.Append(text_Run2);
heading.Append(Run1);
heading.Append(Run2);
body.Append(heading);
但是在运行代码之后,在 word 文件中这些运行得到了 Normal 风格。 我可以对段落应用段落样式但是我不能应用字符样式运行,我的代码哪里错了?
总结:
如何将字符样式应用到运行中以及如何让段落具有不同样式的运行?
最佳答案
您需要在其属性部分中指定段落的格式,否则它将回退到文档的默认设置,在本例中为 Normal
。如果您的自定义样式未保存到文档的样式部分,也可能会发生这种情况。
将您的代码更改为:
Paragraph heading = new Paragraph();
ParagraphProperties heading_pPr = new ParagraphProperties();
heading.Append(heading_pPr);
ParagraphMarkRunProperties headingParagraphMarkRunProperties = new ParagraphMarkRunProperties();
RunStyle runStyle1 = new RunStyle(){ Val = "CharacterStyle1" };
headingParagraphMarkRunProperties.Append(runStyle1);
heading_pPr.Append(headingParagraphMarkRunProperties);
这将使您的段落采用您的自定义格式。您仍然需要将单独的样式应用于 run
元素以更改其格式,就像您在其余代码中所做的那样。
关于c# - 在 c# 中使用 openxml 进行文字处理时一行中的不同样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15679402/