Open XML: Set heading style

If you create a word document and fill it with content, you will normally define headings to group the content. So it is a common task to define and use heading styles. There are two main uses cases: you may use existing heading styles or you want to create new ones.

Within this article I want to show you how to use existing styles. So your word document is based on a template you have to create. In a follow up article I will show you how to create new heading styles.

At first you have to create a template document. This may be an empty word document or with a dummy heading so that the styles are exported to this document. At second you have to know the names of the styles included in your template. The word document is an Open XML zip container. Therefore you can rename the extension to zip and analyze the content of the container. There you will find a styles.xml document. Open it and look for the names of you heading styles. Each style has a style ID and a name. The ID is used to assign styles and the name may be used by applications to show it to the user. The IDs and names of your styles depend on the language settings of you application. For example the ID for the heading 1 may be heading1 if you have an English installation or berschrift1 if you have a German installation.

The following source code shows how to use the template and how to set the heading style. At first a new file will be created as copy of the template. Afterwards you have to open the new file and add your heading text by creating a Paragraph with included Run and Text element. The heading style will be set as property of the Paragraph. So you have to create a ParagraphProperties element and assign a ParagraphStyleId element which contains the name of the heading style.

//file name
string folder = @"<my folder>";
string fileName = folder + @"\Test.docx";
string fileNameTemplate = folder + @"\Template.docx";

//copy template file
if (File.Exists(fileName) == true)
{
    File.Delete(fileName);
}

File.Copy(fileNameTemplate, fileName);

//open file
var file = WordprocessingDocument.Open(fileName, true);            

//define content
var text = new Text("Hello world");
var run = new Run(text);
var paragraph = new Paragraph(run);
paragraph.ParagraphProperties = new ParagraphProperties(
    new ParagraphStyleId() { Val = "berschrift1" });            
            
file.MainDocumentPart.Document.Body.AppendChild(paragraph);
file.MainDocumentPart.Document.Save();
Werbung
Dieser Beitrag wurde unter .NET, C#, Open XML veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit deinem WordPress.com-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s