简体   繁体   中英

Applying Style To A Document

How can I apply a style to a document like "CSS", but programmatically with OpenXML? I don't want to apply style to individual elements, but set defaults and have the document parts obey them.

I've found HTMLToOpenXML, but would prefer doing this myself. Any help would be appreciated.

Solved it, just use the OpenXML Productivity Tool, find the name of the part you looking. Alternatively just open up the document and identify what you looking to change, like a Header or Part A or Normal.

Here's the code with sample changes:

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;
                    }
                }

            }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM