次の方法で共有


段落スタイルを作成してワープロ ドキュメントに追加する

このトピックでは、Open XML SDK for Office のクラスを使用してプログラムで段落スタイルを作成し、ワープロ ドキュメントに追加する方法について説明します。 このタスクを示す CreateAndAddParagraphStyle メソッドの例と、必要に応じてスタイル パーツを追加する補足的なサンプル メソッドが含まれています。


CreateAndAddParagraphStyle メソッド

CreateAndAddParagraphStyleサンプル メソッドを使用して、ワープロ ドキュメントにスタイルを追加できます。 最初に、スタイルを追加するドキュメントにあるスタイル定義パーツへの参照を取得する必要があります。 取得方法の詳細と例については、「サンプル メソッドの呼び出し」セクションを参照してください。

このメソッドは、4 つのパラメーターを受け取ります。各パラメーターにはそれぞれ、スタイル定義パーツへの参照、スタイルのスタイル ID (内部識別子)、(ユーザー インターフェイスで外部使用するための) スタイルの名前、およびオプションでスタイルのエイリアス (ユーザー インターフェイスで使用する代替名) を指定します。

static void CreateAndAddParagraphStyle(StyleDefinitionsPart styleDefinitionsPart, string styleid, string stylename, string aliases = "")

このメソッドの完全なコードについては、「サンプル コード」セクションを参照してください。


スタイル ID、スタイル名、およびエイリアスについて

スタイル ID は、スタイルを参照するためにドキュメントによって使用され、スタイルの主識別子と考えることができます。 一般的に、スタイル ID は、コードでスタイルを識別するために使用します。 また、スタイルには、ユーザー インターフェイスで使用する別の表示名を指定できます。 多くの場合、スタイル名は、Heading 1 のように適切な大文字と小文字、および間隔で表すのに対し、スタイル ID は、heading1 のように、より簡潔な文字で表します。 エイリアスには、アプリケーションのユーザー インターフェイスで使用できる代替のスタイル名を指定します。

たとえば、スタイル定義から取得した次の XML コード例について考察します。

    <w:style w:type="paragraph" w:styleId="OverdueAmountPara" . . .>
      <w:aliases w:val="Late Due, Late Amount" />
      <w:name w:val="Overdue Amount Para" />
    . . .
    </w:style>

style 要素の styleId 属性には、スタイルの主内部識別子であるスタイル ID (OverdueAmountPara) が格納されています。 aliases 要素には、2 つの代替のスタイル名 (Late Due と Late Amount) が指定されており、コンマで区切られています。 各名前は 1 つ以上のコンマで区切る必要があります。 最後に、name 要素には、主スタイル名 (通常、アプリケーションのユーザー インターフェイスに表示される名前) が指定されています。


サンプル メソッドの呼び出し

Open XML SDK を使用して、 CreateAndAddParagraphStyle のサンプル メソッドを使用して、ワープロ ドキュメントに名前付きスタイルを作成して追加します。 次のコード例は、ワープロ ドキュメントへの参照を開いて取得し、ドキュメントのスタイル定義部分への参照を取得し、 CreateAndAddParagraphStyle メソッドを呼び出す方法を示しています。

メソッドを呼び出すには、1 つ目のパラメーターでスタイル定義パーツへの参照、2 つ目のパラメーターでスタイルのスタイル ID、3 つ目のパラメーターでスタイルの名前、およびオプションの 4 つ目のパラメーターでスタイルのエイリアスを渡します。 たとえば、次のコードでは、"期限切れの金額パラ" 段落スタイルを作成します。 また、テキストの段落を追加し、その段落にスタイルを適用します。

string strDoc = args[0];

using (WordprocessingDocument doc = WordprocessingDocument.Open(strDoc, true))
{
    if (doc is null)
    {
        throw new ArgumentNullException("document could not be opened");
    }

    MainDocumentPart mainDocumentPart = doc.MainDocumentPart ?? doc.AddMainDocumentPart();

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

    // If the Styles part does not exist, add it and then add the style.
    if (part is null)
    {
        part = AddStylesPartToPackage(doc);
    }

    // Set up a variable to hold the style ID.
    string parastyleid = "OverdueAmountPara";

    // Create and add a paragraph style to the specified styles part 
    // with the specified style ID, style name and aliases.
    CreateAndAddParagraphStyle(part, parastyleid, "Overdue Amount Para", "Late Due, Late Amount");

    // Add a paragraph with a run and some text.
    Paragraph p =
        new Paragraph(
            new Run(
                new Text("This is some text in a run in a paragraph.")));

    // Add the paragraph as a child element of the w:body element.
    mainDocumentPart.Document ??= new Document();
    mainDocumentPart.Document.Body ??= new Body();

    mainDocumentPart.Document.Body.AppendChild(p);

    // If the paragraph has no ParagraphProperties object, create one.
    if (p.Elements<ParagraphProperties>().Count() == 0)
    {
        p.PrependChild(new ParagraphProperties());
    }

    // Get a reference to the ParagraphProperties object.
    p.ParagraphProperties ??= new ParagraphProperties();
    ParagraphProperties pPr = p.ParagraphProperties;

    // If a ParagraphStyleId object doesn't exist, create one.
    pPr.ParagraphStyleId ??= new ParagraphStyleId();

    // Set the style of the paragraph.
    pPr.ParagraphStyleId.Val = parastyleid;
}

スタイルの種類

WordprocessingML では、6 つのスタイルの種類をサポートしています。 そのうち 4 つは、style 要素で type 属性を使用して指定できます。ISO/IEC 29500 仕様の 17.7.4.17 項に記載されている次の情報は、スタイルの種類について説明しています。

スタイルの種類とは、このスタイル定義で作成されるスタイルの種類を定義する、スタイルに関するプロパティのことです。 WordprocessingML では、スタイル定義の type 属性の値によって、次の 6 種類のスタイル定義をサポートしています。

  • 段落スタイル

  • 文字スタイル

  • リンクされたスタイル (段落 + 文字) [メモ: link 要素 (§17.7.4.6) により実現。 メモ終了]

  • 表スタイル

  • 番号付けスタイル

  • 既定の段落と文字のプロパティ

: 次のように、ドキュメントに Heading 1 という名前のスタイルがあるとします。

    <w:style w:type="paragraph" w:styleId="Heading1">
      <w:name w:val="heading 1"/>
      <w:basedOn w:val="Normal"/>
      <w:next w:val="Normal"/>
      <w:link w:val="Heading1Char"/>
      <w:uiPriority w:val="1"/>
      <w:qformat/>
      <w:rsid w:val="00F303CE"/>
      …
    </w:style>

type 属性には、paragraph という値が指定されており、次に続くスタイル定義が段落スタイルであることを示しています。

© ISO/IEC 29500: 2016

style 要素の type 属性に対応する値を指定して、段落、文字、表、および番号付けのスタイルの種類を設定できます。


段落スタイルの種類

段落をスタイルの種類として指定するには、style 要素の type 属性の値を "paragraph" に設定します。

ISO/IEC 29500 仕様の 17.7.8 項に記載されている次の情報は、段落スタイルについて説明しています。 § の後に続く項番号は、ISO 仕様の項を表しています。

17.7.8 段落スタイル

段落スタイルは、段落全体の内容および段落記号に適用されるスタイルです。 この定義は、文字プロパティ (ドキュメント内のテキストに適用されるプロパティ) と段落プロパティ (段落の配置と表示形式に適用されるプロパティ) の両方を、このスタイルで定義できることを示しています。 Paragraph styles cannot be referenced by runs within a document; they shall be referenced by the pStyle element (§17.3.1.27) within a paragraph's paragraph properties element.

段落スタイルには、定義スタイルの種類固有の特性が 3 つあります。

  • スタイルの type 属性には、値 paragraph が格納され、次に続くスタイル定義が段落スタイルであることを示しています。

  • next 要素では、段落スタイルを供給する編集動作を定義します。この編集動作は、このスタイルの段落の最後で Enter キーを押したときに自動的に次の段落に適用されます。

  • スタイルでは、それぞれ pPr 要素と rPr 要素を使用して、段落レベルと文字レベルのプロパティを指定します。 この場合、セクション プロパティは、段落の各セクションに適用されるプロパティのセットです。

段落スタイルは、段落プロパティの pStyle 要素でこのスタイルの styleId 属性値を参照すると、段落に適用されます。

© ISO/IEC 29500: 2016


コードの動作のしくみ

CreateAndAddParagraphStyle メソッドは、スタイル パーツ内の styles 要素への参照を取得することから始まります。 styles 要素は、このパーツのルート要素で、個別の style 要素がすべて格納されています。 参照が null の場合、styles 要素が作成されます。

// Access the root element of the styles part.
Styles? styles = styleDefinitionsPart.Styles;

if (styles is null)
{
    styleDefinitionsPart.Styles = new Styles();
    styles = styleDefinitionsPart.Styles;
}

スタイルを作成する

スタイルを作成するために、コードは Style クラスをインスタンス化し、スタイルの Type (段落)、 StyleId、スタイルが CustomStyleかどうか、スタイルがその型の Default スタイルであるかどうかを示す特定のプロパティを設定します。

// Create a new paragraph style element and specify some of the attributes.
Style style = new Style()
{
    Type = StyleValues.Paragraph,
    StyleId = styleid,
    CustomStyle = true,
    Default = false
};

このコードの実行結果が、次の XML です。

    <w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
      <w:style w:type="paragraph" w:styleId="OverdueAmountPara" w:default="false" w:customStyle="true">
      </w:style>
    </w:styles>

コードは次に、スタイルの子要素を作成し、それらの子要素がスタイルのプロパティを定義します。 要素を作成するには、対応するクラスをインスタンス化し、 Append メソッドを呼び出して、子要素をスタイルに追加します。 これらのプロパティの詳細については、ISO/IEC 29500 仕様書のセクション 17.7 をご覧ください。

// Create and add the child elements (properties of the style).
Aliases aliases1 = new Aliases() { Val = aliases };
AutoRedefine autoredefine1 = new AutoRedefine() { Val = OnOffOnlyValues.Off };
BasedOn basedon1 = new BasedOn() { Val = "Normal" };
LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountChar" };
Locked locked1 = new Locked() { Val = OnOffOnlyValues.Off };
PrimaryStyle primarystyle1 = new PrimaryStyle() { Val = OnOffOnlyValues.On };
StyleHidden stylehidden1 = new StyleHidden() { Val = OnOffOnlyValues.Off };
SemiHidden semihidden1 = new SemiHidden() { Val = OnOffOnlyValues.Off };
StyleName styleName1 = new StyleName() { Val = stylename };
NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle() { Val = "Normal" };
UIPriority uipriority1 = new UIPriority() { Val = 1 };
UnhideWhenUsed unhidewhenused1 = new UnhideWhenUsed() { Val = OnOffOnlyValues.On };

if (string.IsNullOrWhiteSpace(aliases))
{
    style.Append(aliases1);
}

style.Append(autoredefine1);
style.Append(basedon1);
style.Append(linkedStyle1);
style.Append(locked1);
style.Append(primarystyle1);
style.Append(stylehidden1);
style.Append(semihidden1);
style.Append(styleName1);
style.Append(nextParagraphStyle1);
style.Append(uipriority1);
style.Append(unhidewhenused1);

次に、 StyleRunProperties オブジェクトをインスタンス化して、 rPr (プロパティの実行) 要素を作成します。 この要素では、フォント、色など、スタイルに適用する文字プロパティを指定します。 プロパティは、 rPr 要素の子として追加されます。

実行プロパティを作成すると、 rPr 要素がスタイルに追加され、style 要素がスタイル パーツの styles ルート要素に追加されます。

// Create the StyleRunProperties object and specify some of the run properties.
StyleRunProperties styleRunProperties1 = new StyleRunProperties();
Bold bold1 = new Bold();
Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 };
RunFonts font1 = new RunFonts() { Ascii = "Lucida Console" };
Italic italic1 = new Italic();

// Specify a 12 point size.
FontSize fontSize1 = new FontSize() { Val = "24" };
styleRunProperties1.Append(bold1);
styleRunProperties1.Append(color1);
styleRunProperties1.Append(font1);
styleRunProperties1.Append(fontSize1);
styleRunProperties1.Append(italic1);

// Add the run properties to the style.
style.Append(styleRunProperties1);

// Add the style to the styles part.
styles.Append(style);

段落スタイルを適用する

スタイルを作成した後で、段落プロパティの pStyle 要素でこのスタイルの styleId 属性値を参照すると、スタイルを段落に適用できます。 次のコード例では、変数 p によって参照される段落にスタイルを適用する方法を示しています。 適用するスタイルのスタイル ID は parastyleid 変数に格納され、ParagraphStyleId プロパティは段落プロパティの pStyle 要素を表します。

// If the paragraph has no ParagraphProperties object, create one.
if (p.Elements<ParagraphProperties>().Count() == 0)
{
    p.PrependChild(new ParagraphProperties());
}

// Get a reference to the ParagraphProperties object.
p.ParagraphProperties ??= new ParagraphProperties();
ParagraphProperties pPr = p.ParagraphProperties;

// If a ParagraphStyleId object doesn't exist, create one.
pPr.ParagraphStyleId ??= new ParagraphStyleId();

// Set the style of the paragraph.
pPr.ParagraphStyleId.Val = parastyleid;

サンプル コード

C# と Visual Basic の両方の完全な CreateAndAddParagraphStyle コード サンプルを次に示します。

// Create a new paragraph style with the specified style ID, primary style name, and aliases and 
// add it to the specified style definitions part.
static void CreateAndAddParagraphStyle(StyleDefinitionsPart styleDefinitionsPart, string styleid, string stylename, string aliases = "")
{
    // Access the root element of the styles part.
    Styles? styles = styleDefinitionsPart.Styles;

    if (styles is null)
    {
        styleDefinitionsPart.Styles = new Styles();
        styles = styleDefinitionsPart.Styles;
    }

    // Create a new paragraph style element and specify some of the attributes.
    Style style = new Style()
    {
        Type = StyleValues.Paragraph,
        StyleId = styleid,
        CustomStyle = true,
        Default = false
    };

    // Create and add the child elements (properties of the style).
    Aliases aliases1 = new Aliases() { Val = aliases };
    AutoRedefine autoredefine1 = new AutoRedefine() { Val = OnOffOnlyValues.Off };
    BasedOn basedon1 = new BasedOn() { Val = "Normal" };
    LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountChar" };
    Locked locked1 = new Locked() { Val = OnOffOnlyValues.Off };
    PrimaryStyle primarystyle1 = new PrimaryStyle() { Val = OnOffOnlyValues.On };
    StyleHidden stylehidden1 = new StyleHidden() { Val = OnOffOnlyValues.Off };
    SemiHidden semihidden1 = new SemiHidden() { Val = OnOffOnlyValues.Off };
    StyleName styleName1 = new StyleName() { Val = stylename };
    NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle() { Val = "Normal" };
    UIPriority uipriority1 = new UIPriority() { Val = 1 };
    UnhideWhenUsed unhidewhenused1 = new UnhideWhenUsed() { Val = OnOffOnlyValues.On };

    if (string.IsNullOrWhiteSpace(aliases))
    {
        style.Append(aliases1);
    }

    style.Append(autoredefine1);
    style.Append(basedon1);
    style.Append(linkedStyle1);
    style.Append(locked1);
    style.Append(primarystyle1);
    style.Append(stylehidden1);
    style.Append(semihidden1);
    style.Append(styleName1);
    style.Append(nextParagraphStyle1);
    style.Append(uipriority1);
    style.Append(unhidewhenused1);

    // Create the StyleRunProperties object and specify some of the run properties.
    StyleRunProperties styleRunProperties1 = new StyleRunProperties();
    Bold bold1 = new Bold();
    Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 };
    RunFonts font1 = new RunFonts() { Ascii = "Lucida Console" };
    Italic italic1 = new Italic();

    // Specify a 12 point size.
    FontSize fontSize1 = new FontSize() { Val = "24" };
    styleRunProperties1.Append(bold1);
    styleRunProperties1.Append(color1);
    styleRunProperties1.Append(font1);
    styleRunProperties1.Append(fontSize1);
    styleRunProperties1.Append(italic1);

    // Add the run properties to the style.
    style.Append(styleRunProperties1);

    // Add the style to the styles part.
    styles.Append(style);
}

// Add a StylesDefinitionsPart to the document.  Returns a reference to it.
static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument? doc)
{
    StyleDefinitionsPart part;

    if (doc?.MainDocumentPart is null)
    {
        throw new ArgumentNullException("MainDocumentPart is null.");
    }

    part = doc.MainDocumentPart.AddNewPart<StyleDefinitionsPart>();
    part.Styles = new Styles();

    return part;
}

string strDoc = args[0];

using (WordprocessingDocument doc = WordprocessingDocument.Open(strDoc, true))
{
    if (doc is null)
    {
        throw new ArgumentNullException("document could not be opened");
    }

    MainDocumentPart mainDocumentPart = doc.MainDocumentPart ?? doc.AddMainDocumentPart();

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

    // If the Styles part does not exist, add it and then add the style.
    if (part is null)
    {
        part = AddStylesPartToPackage(doc);
    }

    // Set up a variable to hold the style ID.
    string parastyleid = "OverdueAmountPara";

    // Create and add a paragraph style to the specified styles part 
    // with the specified style ID, style name and aliases.
    CreateAndAddParagraphStyle(part, parastyleid, "Overdue Amount Para", "Late Due, Late Amount");

    // Add a paragraph with a run and some text.
    Paragraph p =
        new Paragraph(
            new Run(
                new Text("This is some text in a run in a paragraph.")));

    // Add the paragraph as a child element of the w:body element.
    mainDocumentPart.Document ??= new Document();
    mainDocumentPart.Document.Body ??= new Body();

    mainDocumentPart.Document.Body.AppendChild(p);

    // If the paragraph has no ParagraphProperties object, create one.
    if (p.Elements<ParagraphProperties>().Count() == 0)
    {
        p.PrependChild(new ParagraphProperties());
    }

    // Get a reference to the ParagraphProperties object.
    p.ParagraphProperties ??= new ParagraphProperties();
    ParagraphProperties pPr = p.ParagraphProperties;

    // If a ParagraphStyleId object doesn't exist, create one.
    pPr.ParagraphStyleId ??= new ParagraphStyleId();

    // Set the style of the paragraph.
    pPr.ParagraphStyleId.Val = parastyleid;
}

関連項目