使用 C# / .NET 和 Microsoft 的 DocumentFormat.OpenXml Nuget 包,我尝试修改 DOCX 文件,以便整个文档的格式设置为斜体。
但是,输出文档比我在 Word 中进行更改要大得多
(CTRL+A、CTRL+I、CTRL+S)。
private void ModifyDocument(string filePath)
{
using (WordprocessingDocument document = WordprocessingDocument.Open(filePath, true))
{
var body = document.MainDocumentPart.Document.Body;
// Iterate through all paragraphs and modify text formatting
foreach (var paragraph in body.Elements<Paragraph>())
{
foreach (var run in paragraph.Elements<Run>())
{
// Retrieve existing RunProperties or create a new one
var runProperties = run.GetFirstChild<RunProperties>();
if (runProperties == null)
{
runProperties = new RunProperties();
run.PrependChild(runProperties);
}
// Modify font to Times New Roman and italicize the text
runProperties.RunFonts = new RunFonts { Ascii = "Times New Roman", HighAnsi = "Times New Roman" };
runProperties.Italic = new Italic();
}
}
document.MainDocumentPart.Document.Save(); // Save changes
}
}
您会推荐什么方法来代替这个:
谢谢!
试试这个:
private void ModifyDocument(string filePath)
{
using (var document = WordprocessingDocument.Open(filePath, true))
{
var styles = document.MainDocumentPart.StyleDefinitionsPart.Styles;
// Get "<w:docDefaults>".
var docDefaults = styles.Elements<DocDefaults>().First();
// Get "<w:rPrDefault>".
var rPrDefault = docDefaults.RunPropertiesDefault;
// Get "<w:rPr>".
var rPr = rPrDefault.RunPropertiesBaseStyle;
// Add "<w:i/>".
rPr.Italic = new Italic();
styles.Save();
}
}
它将把
Italic
添加到文档的默认字符格式中。