更改OpenXML Word文档(C#)中的字体颜色

问题描述 投票:10回答:4

我一直在搜索几个小时,但似乎找不到一个可靠的答案。我有一个带有内容控件的现有文档,我需要使用外部数据来编辑文本。如果不存在其中一个控件的数据,则需要用适当的提示替换文本并更改字体颜色。

我有文本输入项,并且一切正常,唯一似乎无法完成工作的部分就是更改字体颜色。我当前使用的代码不会给我任何错误,并且可以通过此方法正常运行,但是当我查看完成的文档时,它仍然是纯黑色文本。

我的颜色更改方法:(输入是带有相同标签的所有内容控件的列表)

public void SetBlueText(List<SdtElement> sdtElement)
{
    foreach (SdtElement element in sdtElement)
    {
        if (element != null)
        {
            RunProperties runProperties = element.Descendants<RunProperties>().FirstOrDefault();
            runProperties.Color = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "0EBFE9" };
        }
    }
}

此外,将这两行简化为/具有相同的效果

element.Descendants<RunProperties>().FirstOrDefault().Color = 
                        new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "0EBFE9" };
c# openxml
4个回答
14
投票

我遇到类似的问题,并且发现由于某种原因,将对象追加到RunProperties对象的顺序实际上会影响格式更新是否有效(我注意到的模式是,如果您在格式化之前先添加文本, ,该文本的格式不会保留)。

例如这有效(文本变为粗体,Cambria Headings,并且颜色设置为蓝色)

Run formattedRun = new Run();
RunProperties runPro = new RunProperties();
RunFonts runFont = new RunFonts() { Ascii = "Cambria(Headings)", HighAnsi = "Cambria(Headings)" };
Bold bold = new Bold();
Text text = new Text("TESTING");
Color color = new Color() { Val = "365F91", ThemeColor = ThemeColorValues.Accent1, ThemeShade = "BF" };
runPro.Append(runFont);
runPro.Append(bold);
runPro.Append(color);
runPro.Append(text);
formattedRun.Append(runPro);

但是不是(文本变成Cambria Headings and Bold,但颜色保持标准黑色)

Run formattedRun = new Run();
RunProperties runPro = new RunProperties();
RunFonts runFont = new RunFonts() { Ascii = "Cambria(Headings)", HighAnsi = "Cambria(Headings)" };
Text text = new Text("TESTING");
Bold bold = new Bold();
Color color = new Color() { Val = "365F91", ThemeColor = ThemeColorValues.Accent1, ThemeShade = "BF" };
runPro.Append(runFont);
runPro.Append(bold);
runPro.Append(text);
runPro.Append(color);
formattedRun.Append(runPro);

5
投票

好吧,我有点蛮横地逼迫我回答问题,但确实可行。

List<RunProperties> runProps = element.Descendants<RunProperties>().ToList();
foreach (RunProperties rp in runProps)
{
    rp.Color = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "0EBFE9" };
}

[如果有人有更优雅的解决方案,请添加它,我会投票赞成。


0
投票

我需要一个与OP非常相似的东西,因为我在运行时填充的Word文档模板中有一堆纯文本和其他控件。我创建了一个扩展方法来设置文本和其他格式的位和鲍勃。希望这会像我一样帮助任何需要帮助的人:

    public static void ReplaceText(this SdtElement element, string replacementText, bool? isBold = null, bool? isItalic = null, System.Drawing.Color? color = null, VerticalPositionValues? textVerticalType = null, int? fontSizeComplexScript = null)
    {

        // First try to get content blocks from the element
        IEnumerable<SdtContentBlock> childContentBlocks = element.ChildElements.OfType<SdtContentBlock>();

        //Function to generate the new run properties
        RunProperties SetupNewRunProperties(RunProperties oldRunProps) { 

            var props = new RunProperties();

            if (fontSizeComplexScript.HasValue && fontSizeComplexScript.HasValue)
                props.FontSizeComplexScript.Val = fontSizeComplexScript.ToString();
            else if (oldRunProps?.FontSizeComplexScript != null)
                props.FontSizeComplexScript = (FontSizeComplexScript)oldRunProps.FontSizeComplexScript.CloneNode(true);

            if (isBold.HasValue) 
                props.Bold.Val = OnOffValue.FromBoolean(isBold.Value);
            else if(oldRunProps?.Bold != null)
                props.Bold = (Bold)oldRunProps.Bold.CloneNode(true);

            if (isItalic.HasValue)
                props.Italic.Val = OnOffValue.FromBoolean(isItalic.Value);
            else if (oldRunProps?.Italic != null)
                props.Italic = (Italic)oldRunProps.Italic.CloneNode(true);

            if (textVerticalType.HasValue)
                props.VerticalTextAlignment.Val = textVerticalType.Value;
            else if (oldRunProps?.VerticalTextAlignment != null)
                props.VerticalTextAlignment = (VerticalTextAlignment)oldRunProps.VerticalTextAlignment.CloneNode(true);

            if (color.HasValue)
            {
                if (props.Color != null)
                    props.Color.Val = color.Value.ToHexString();
                else
                    props.Color = new Color() { Val = color.Value.ToHexString() };
            }
            else if (oldRunProps?.Color != null)
            {
                props.Color = (Color)oldRunProps?.Color.CloneNode(true);
            }

            return props;
        }

        if (childContentBlocks.Count() > 0)
        {
            SdtContentBlock contentBlock = childContentBlocks.First();
            Paragraph para = contentBlock.ChildElements.OfType<Paragraph>().First();
            if (para != null)
            {
                Run run = para.GetFirstChild<Run>();

                run.RunProperties = SetupNewRunProperties(run.RunProperties);

                Text text = run.GetFirstChild<Text>();
                text.Text = replacementText;
            }
        }
        else
        {
            // Instead, try to get content runs from the element
            IEnumerable<SdtContentRun> childContentRuns = element.ChildElements.OfType<SdtContentRun>();

            if (childContentRuns.Count() > 0)
            {
                Run run = childContentRuns.First().GetFirstChild<Run>();

                run.RunProperties = SetupNewRunProperties(run.RunProperties);

                Text text = run.GetFirstChild<Text>();
                text.Text = replacementText;
            }
        }

    }

-1
投票

颜色值应为8位数字。例如Color.Val =“ FFFF0000”用红色显示字符串。

© www.soinside.com 2019 - 2024. All rights reserved.