You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# OpenXML中葡萄牙语特殊字符无法应用Times New Roman字体的问题

解决OpenXML中葡萄牙语特殊字符字体不生效问题

问题原因

你仅给RunFonts设置了Ascii属性,而葡萄牙语的Ç、Ã这类非ASCII的拉丁扩展字符,Word会优先使用HighAnsi字体配置。默认情况下HighAnsi字体为Calibri,因此这些特殊字符未应用Times New Roman。

解决方案

创建RunFonts对象时,同时指定Ascii和HighAnsi属性为Times New Roman,覆盖默认字体配置:

var runFont0 = new RunFonts { Ascii = "Times New Roman", HighAnsi = "Times New Roman" };

修改后的完整代码

public static void CreateWordprocessingDocument_teste(string filepath)
{
    using (WordprocessingDocument wordDocument =
        WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
    {
        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

        mainPart.Document = new Document();
        Body body = mainPart.Document.AppendChild(new Body());


        Text text0 = new Text() { Text = "PROCURAÇÃO", Space = SpaceProcessingModeValues.Preserve };


        Run run0 = new Run();

        Paragraph para0 = new Paragraph();

        ParagraphProperties paragraphProperties0 = new ParagraphProperties();
        SpacingBetweenLines spaceBetweenLines0 = new SpacingBetweenLines();
        ParagraphStyleId paragraphStyleId0 = new ParagraphStyleId() { Val = "Normal" };
        Justification justification0 = new Justification() { Val = JustificationValues.Center };
        ParagraphMarkRunProperties paragraphMarkRunProperties0 = new ParagraphMarkRunProperties();

        paragraphProperties0.Append(paragraphStyleId0);
        paragraphProperties0.Append(justification0);
        paragraphProperties0.Append(paragraphMarkRunProperties0);

        RunProperties runProperties0 = new RunProperties();
        var size0 = new FontSize { Val = new StringValue("24") };
        // 同时设置Ascii和HighAnsi字体
        var runFont0 = new RunFonts { Ascii = "Times New Roman", HighAnsi = "Times New Roman" };
        runProperties0.Append(new Bold());
        runProperties0.Append(new Underline() { Val = DocumentFormat.OpenXml.Wordprocessing.UnderlineValues.Single });
        runProperties0.Append(runFont0);
        runProperties0.Append(size0);

        run0.Append(runProperties0);
        run0.Append(text0);
        para0.Append(paragraphProperties0);
        para0.Append(run0);

        body.AppendChild(para0);
    }
}

内容的提问来源于stack exchange,提问作者Felisberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:30:24