在 C# .NET 中使用 DocumentFormat.OpenXml 使整个 DOCX 变为斜体

问题描述 投票:0回答:1

使用 C# / .NET 和 Microsoft 的 DocumentFormat.OpenXml Nuget 包,我尝试修改 DOCX 文件,以便整个文档的格式设置为斜体。

但是,输出文档比我在 Word 中进行更改要大得多
CTRL+ACTRL+ICTRL+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
    }
}

您会推荐什么方法来代替这个:

谢谢!

c# .net openxml docx
1个回答
0
投票

试试这个:

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
添加到文档的默认字符格式中。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.