将样式应用于文档

时间:2013-02-18 08:59:51

标签: c# openxml openxml-sdk

如何将样式应用于像“CSS”这样的文档,但是使用OpenXML以编程方式? 我不想将样式应用于单个元素,但设置默认值并使文档部分遵守它们。

我找到了HTMLToOpenXML,但我更喜欢自己这样做。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

解决它,只需使用OpenXML Productivity Tool,找到您所查找的部件的名称。或者,只需打开文档并确定您要更改的内容,例如标题或A部分或正常。

以下是包含示例更改的代码:

public static void GetAndSetStyleFromDoc(string file)
{
            bool styleExists = true;

            using (var document = WordprocessingDocument.Open(file,true))
            {

                // Get the Styles part for this document
                StyleDefinitionsPart part = document.MainDocumentPart.StyleDefinitionsPart;

                foreach (Style style in part.RootElement.Elements<Style>())
                {
                    // PartA can be changed for "Normal", "Header1" etc
                    if (style.StyleId.Value.Equals("PartA", StringComparison.InvariantCultureIgnoreCase))
                    {
                        style.StyleParagraphProperties.SpacingBetweenLines.Line = "276";
                        style.StyleRunProperties.FontSize.Val = "14";
                        style.StyleRunProperties.Color.Val = "4F81BD"; // font color

                        ParagraphBorders paragraphBorders1 = new ParagraphBorders();
                        TopBorder topBorder1 = new TopBorder(){ Val = BorderValues.Single, Color = "856363", Size = (UInt32Value)24U, Space = (UInt32Value)0U };
                        LeftBorder leftBorder1 = new LeftBorder(){ Val = BorderValues.Single, Color = "856363", Size = (UInt32Value)24U, Space = (UInt32Value)0U };
                        BottomBorder bottomBorder1 = new BottomBorder(){ Val = BorderValues.Single, Color = "856363", Size = (UInt32Value)24U, Space = (UInt32Value)0U };
                        RightBorder rightBorder1 = new RightBorder(){ Val = BorderValues.Single, Color = "856363", Size = (UInt32Value)24U, Space = (UInt32Value)0U };

                        paragraphBorders1.Append(topBorder1);
                        paragraphBorders1.Append(leftBorder1);
                        paragraphBorders1.Append(bottomBorder1);
                        paragraphBorders1.Append(rightBorder1);

                        style.StyleParagraphProperties.ParagraphBorders = paragraphBorders1;
                    }
                }

            }
}