文字スタイルを作成してワープロ ドキュメントに追加する
このトピックでは、Open XML SDK for Office のクラスを使用して、プログラムによって文字スタイルを作成し、ワープロ ドキュメントに追加する方法について説明します。 このタスクを示す CreateAndAddCharacterStyle
メソッドの例と、必要に応じてスタイル パーツを追加する補足的なサンプル メソッドが含まれています。
CreateAndAddCharacterStyle メソッド
CreateAndAddCharacterStyle
サンプル メソッドを使用して、ワープロ ドキュメントにスタイルを追加できます。 最初に、スタイルを追加するドキュメントにあるスタイル定義パーツへの参照を取得する必要があります。 これを行う方法を示す例については、「 サンプル メソッドの呼び出し 」セクションを参照してください。
メソッドは、編集するファイルへのパス、スタイルのスタイル ID (内部識別子)、スタイルの名前 (ユーザー インターフェイスで外部で使用するため)、必要に応じて任意のスタイル エイリアス (ユーザー インターフェイスで使用する代替名) を示す 4 つのパラメーターを受け入れます。
static void CreateAndAddCharacterStyle(string filePath, string styleid, string stylename, string aliases = "")
このメソッドの完全なコードについては、「サンプル コード」セクションを参照してください。
スタイル ID、スタイル名、およびエイリアスについて
スタイル ID は、スタイルを参照するためにドキュメントによって使用され、スタイルの主識別子と考えることができます。 一般的に、スタイル ID は、コードでスタイルを識別するために使用します。 また、スタイルには、ユーザー インターフェイスに表示される別の表示名を指定できます。 多くの場合、スタイル名は、Heading 1 のように適切な大文字と小文字、および間隔で表すのに対し、スタイル ID は、heading1 のように、より簡潔な文字で表します。 エイリアスには、アプリケーションのユーザー インターフェイスで使用できる代替のスタイル名を指定します。
たとえば、スタイル定義から取得した次の XML コード例について考察します。
<w:style w:type="character" w:styleId="OverdueAmountChar" . . .
<w:aliases w:val="Late Due, Late Amount" />
<w:name w:val="Overdue Amount Char" />
. . .
</w:style>
style 要素styleId
属性は、スタイルのメイン内部識別子であるスタイル ID (OverdueAmountChar) を定義します。 aliases 要素には、2 つの代替のスタイル名 (Late Due と Late Amount) が指定されており、コンマで区切られています。 各名前は 1 つ以上のコンマで区切る必要があります。
最後に、name 要素には、主スタイル名 (通常、アプリケーションのユーザー インターフェイスに表示される名前) が指定されています。
サンプル メソッドの呼び出し
CreateAndAddCharacterStyle
のサンプル メソッドを使用して、Open XML SDK を使用して名前付きスタイルを作成し、ワープロ ドキュメントに追加できます。 次のコード例は、ワープロ ドキュメントへの参照を開いて取得し、ドキュメントのスタイル定義パーツへの参照を取得し、 CreateAndAddCharacterStyle
メソッドを呼び出す方法を示しています。
メソッドを呼び出すには、最初のパラメーターとして編集するファイルへの参照、2 番目のパラメーターとしてのスタイル ID、3 番目のパラメーターとしてのスタイルの名前、および必要に応じて 4 番目のパラメーターとして任意のスタイルエイリアスを渡します。 たとえば、次のコード例では、名前がメソッドの最初の引数から取得されるサンプル ファイルに "期限切れの金額 Char" 文字スタイルを作成します。 また、段落に 3 つのテキスト セクションを作成し、2 つ目のセクションにスタイルを適用します。
static void AddStylesToPackage(string filePath)
{
// Create and add the character style with the style id, style name, and
// aliases specified.
CreateAndAddCharacterStyle(
filePath,
"OverdueAmountChar",
"Overdue Amount Char",
"Late Due, Late Amount");
using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
{
// Add a paragraph with a run with some text.
Paragraph p = new Paragraph(
new Run(
new Text("this is some text ") { Space = SpaceProcessingModeValues.Preserve }));
// Add another run with some text.
p.AppendChild<Run>(new Run(new Text("in a run ") { Space = SpaceProcessingModeValues.Preserve }));
// Add another run with some text.
p.AppendChild<Run>(new Run(new Text("in a paragraph.") { Space = SpaceProcessingModeValues.Preserve }));
// Add the paragraph as a child element of the w:body.
doc?.MainDocumentPart?.Document?.Body?.AppendChild(p);
// Get a reference to the second run (indexed starting with 0).
Run r = p.Descendants<Run>().ElementAtOrDefault(1)!;
// If the Run has no RunProperties object, create one and get a reference to it.
RunProperties rPr = r.RunProperties ?? r.PrependChild(new RunProperties());
// Set the character style of the run.
if (rPr.RunStyle is null)
{
rPr.RunStyle = new RunStyle();
rPr.RunStyle.Val = "OverdueAmountChar";
}
}
}
スタイルの種類
WordprocessingML では、6 つのスタイルの種類をサポートしています。 そのうち 4 つは、style 要素で type 属性を使用して指定できます。ISO/IEC 29500 仕様の 17.7.4.17 項に記載されている次の情報は、スタイルの種類について説明しています。
スタイルの種類とは、このスタイル定義で作成されるスタイルの種類を定義する、スタイルに関するプロパティのことです。 WordprocessingML では、スタイル定義の type 属性の値によって、次の 6 種類のスタイル定義をサポートしています。
- 段落スタイル
- 文字スタイル
- リンクされたスタイル (段落 + 文字) リンク要素 (§17.7.4.6) を介して実行されます。
- 表スタイル
- 番号付けスタイル
- 既定の段落 + 文字プロパティ
次のコード例に示すように、ドキュメントの見出し 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 が格納されており、次に続くスタイル定義が段落スタイルであることを示しています。
style 要素の type 属性に対応する値を指定して、段落、文字、表、および番号付けのスタイルの種類を設定できます。
文字スタイルの種類
文字をスタイルの種類として指定するには、style 要素の type 属性の値を "character" に設定します。
ISO/IEC 29500 仕様の 17.7.9 項に記載されている次の情報は、文字スタイルについて説明しています。 § の後に続く項番号は、ISO 仕様の項を表しています。
17.7.9 セクション (文字) スタイル
文字スタイルは、ドキュメントのコンテンツに含まれるテキストの 1 つ以上のセクションのコンテンツに適用されるスタイルです。 この定義は、このスタイルが段落には適用できないため、文字プロパティ (ドキュメント内のテキストに適用されるプロパティ) のみを定義できることを示しています。
文字スタイルは、ドキュメント内の実行によってのみ参照でき、実行の実行プロパティ要素内の rStyle
要素によって参照されます。
文字スタイルには、定義スタイルの種類固有の特性が 2 つあります。
スタイルの type 属性には、値 character が格納され、次に続くスタイル定義が文字スタイルであることを示しています。
スタイルでは、
rPr
要素を使用して文字レベルのプロパティのみを指定します。 この場合、セクション プロパティは、このスタイルの各セクションに適用されるプロパティのセットです。
その後、実行プロパティの rStyle
要素で、このスタイルのstyleId
属性値を参照することで、文字スタイルが実行に適用されます。
次の画像は、文字スタイルが適用されたテキストを示しています。 文字スタイルは、テキストの副段落レベル範囲にのみ適用できます。
図 1. 文字スタイルが適用されたテキスト
コードの動作のしくみ
CreateAndAddCharacterStyle
メソッドは、まず、指定したファイルを開き、スタイル パーツ内の styles 要素への参照を取得します。 styles 要素は、このパーツのルート要素で、個別の style 要素がすべて格納されています。 参照が null の場合、styles 要素が作成され、パーツに保存されます。
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filePath, true))
{
// Get access to the root element of the styles part.
Styles? styles = wordprocessingDocument?.MainDocumentPart?.StyleDefinitionsPart?.Styles ?? AddStylesPartToPackage(wordprocessingDocument).Styles;
スタイルを作成する
スタイルを作成するために、コードは Style クラスをインスタンス化し、スタイル (段落) の Type 、 StyleId、スタイルが CustomStyleかどうかなど、特定のプロパティを設定します。
// Create a new character style and specify some of the attributes.
Style style = new Style()
{
Type = StyleValues.Character,
StyleId = styleid,
CustomStyle = true
};
このコードの実行結果が、次の XML です。
<w:style w:type="character" w:styleId="OverdueAmountChar" w:customStyle="true" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
</w:style>
コードは次に、スタイルの子要素を作成し、それらの子要素がスタイルのプロパティを定義します。 要素を作成するには、対応するクラスをインスタンス化し、 Append メソッドを呼び出して、子要素をスタイルに追加します。 これらのプロパティの詳細については、ISO/IEC 29500 仕様書のセクション 17.7 をご覧ください。
// Create and add the child elements (properties of the style).
Aliases aliases1 = new Aliases() { Val = aliases };
StyleName styleName1 = new StyleName() { Val = stylename };
LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountPara" };
if (!String.IsNullOrEmpty(aliases))
{
style.Append(aliases1);
}
style.Append(styleName1);
style.Append(linkedStyle1);
次に、 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 = "Tahoma" };
Italic italic1 = new Italic();
// Specify a 24 point size.
FontSize fontSize1 = new FontSize() { Val = "48" };
styleRunProperties1.Append(font1);
styleRunProperties1.Append(fontSize1);
styleRunProperties1.Append(color1);
styleRunProperties1.Append(bold1);
styleRunProperties1.Append(italic1);
// Add the run properties to the style.
style.Append(styleRunProperties1);
// Add the style to the styles part.
styles.Append(style);
次の XML は、ここに示すコードによって生成される最終スタイルです。
<w:style w:type="character" w:styleId="OverdueAmountChar" w:customStyle="true" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:aliases w:val="Late Due, Late Amount" />
<w:name w:val="Overdue Amount Char" />
<w:link w:val="OverdueAmountPara" />
<w:rPr>
<w:rFonts w:ascii="Tahoma" />
<w:sz w:val="48" />
<w:color w:themeColor="accent2" />
<w:b />
<w:i />
</w:rPr>
</w:style>
文字スタイルの適用
スタイルを作成したら、実行プロパティの rStyle
要素で、このスタイルのstyleId
属性値を参照することで、そのスタイルを実行に適用できます。 次のコード例では、変数 r によって参照されるセクションにスタイルを適用する方法を示しています。 この例では、適用するスタイルのスタイル ID OverdueAmountChar が、 rPr
オブジェクトの RunStyle プロパティに格納されます。 このプロパティは、実行プロパティの rStyle
要素を表します。
// If the Run has no RunProperties object, create one and get a reference to it.
RunProperties rPr = r.RunProperties ?? r.PrependChild(new RunProperties());
// Set the character style of the run.
if (rPr.RunStyle is null)
{
rPr.RunStyle = new RunStyle();
rPr.RunStyle.Val = "OverdueAmountChar";
}
サンプル コード
C# と Visual Basic の両方の完全な CreateAndAddCharacterStyle
コード サンプルを次に示します。
// Create a new character style with the specified style id, style name and aliases and
// add it to the specified file.
static void CreateAndAddCharacterStyle(string filePath, string styleid, string stylename, string aliases = "")
{
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filePath, true))
{
// Get access to the root element of the styles part.
Styles? styles = wordprocessingDocument?.MainDocumentPart?.StyleDefinitionsPart?.Styles ?? AddStylesPartToPackage(wordprocessingDocument).Styles;
if (styles is not null)
{
// Create a new character style and specify some of the attributes.
Style style = new Style()
{
Type = StyleValues.Character,
StyleId = styleid,
CustomStyle = true
};
// Create and add the child elements (properties of the style).
Aliases aliases1 = new Aliases() { Val = aliases };
StyleName styleName1 = new StyleName() { Val = stylename };
LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountPara" };
if (!String.IsNullOrEmpty(aliases))
{
style.Append(aliases1);
}
style.Append(styleName1);
style.Append(linkedStyle1);
// 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 = "Tahoma" };
Italic italic1 = new Italic();
// Specify a 24 point size.
FontSize fontSize1 = new FontSize() { Val = "48" };
styleRunProperties1.Append(font1);
styleRunProperties1.Append(fontSize1);
styleRunProperties1.Append(color1);
styleRunProperties1.Append(bold1);
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>();
Styles root = new Styles();
return part;
}