目次
概要
OpenXML SDKを使用してWord文書を作成する際、段落ごとの配置(左揃え、中央揃え、右揃え、両端揃えなど)をプログラムから制御する実装です。
段落のプロパティ(ParagraphProperties)内に配置情報(Justification)を追加することで、テキストの位置を調整します。
仕様(入出力)
- 入力: ファイルパス、書き込むテキスト、配置指定(
JustificationValues) - 出力: 配置設定が適用された
.docxファイル - ライブラリ: DocumentFormat.OpenXml (NuGetパッケージ)
実装メソッド
| メソッド名 | 説明 |
AppendParagraph | テキストと配置位置(Left, Center, Right 等)を受け取り、指定された配置で段落を追加します。デフォルトは左揃えです。 |
基本の使い方
using DocumentFormat.OpenXml.Wordprocessing;
using var generator = new SimpleWordGenerator("AlignmentTest.docx");
// 左揃え(デフォルト)
generator.AppendParagraph("左寄せのテキストです。");
// 中央揃え
generator.AppendParagraph("中央揃えのタイトル", JustificationValues.Center);
// 右揃え
generator.AppendParagraph("2025年1月1日 右寄せ", JustificationValues.Right);
コード全文
using System;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
class Program
{
static void Main()
{
string filePath = "AlignmentExample.docx";
try
{
Console.WriteLine($"Generating {filePath} ...");
using (var doc = new SimpleWordGenerator(filePath))
{
// 1. 左揃え (Left)
doc.AppendParagraph("これは左揃えの段落です。", JustificationValues.Left);
// 2. 中央揃え (Center)
doc.AppendParagraph("これは中央揃えの段落です。", JustificationValues.Center);
// 3. 右揃え (Right)
doc.AppendParagraph("これは右揃えの段落です。", JustificationValues.Right);
// 4. 両端揃え (Both) - 長い文章で効果を発揮します
string longText = "両端揃えは、行の左右の端がきれいに揃うように文字間隔を自動調整する設定です。" +
"正式な文書やレポートなどで、見た目を整えるためによく使用されます。";
doc.AppendParagraph(longText, JustificationValues.Both);
}
Console.WriteLine("Done.");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
/// <summary>
/// 段落配置に対応したWord文書作成クラス
/// </summary>
public sealed class SimpleWordGenerator : IDisposable
{
private WordprocessingDocument _document;
private Body _body;
public SimpleWordGenerator(string filePath)
{
// 文書とBodyの初期化
_document = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _document.AddMainDocumentPart();
mainPart.Document = new Document();
_body = mainPart.Document.AppendChild(new Body());
}
public void Dispose()
{
_document?.Dispose();
}
/// <summary>
/// 指定された配置で段落を追加します
/// </summary>
/// <param name="text">書き込むテキスト</param>
/// <param name="align">配置(Left, Center, Right, Bothなど)</param>
public void AppendParagraph(string text, JustificationValues align = JustificationValues.Left)
{
// 1. 段落(Paragraph)の生成
var paragraph = new Paragraph();
// 2. 段落プロパティ(ParagraphProperties)の生成
var pPr = new ParagraphProperties();
// 3. 配置設定(Justification)の生成とプロパティへの追加
// Valプロパティに JustificationValues 列挙体をセットします
var justification = new Justification() { Val = align };
pPr.Append(justification);
// 4. プロパティを段落に適用
paragraph.Append(pPr);
// 5. テキスト部分(Run > Text)の生成と追加
var run = new Run();
run.Append(new Text(text));
paragraph.Append(run);
// 6. Bodyに追加
_body.Append(paragraph);
}
}
カスタムポイント
- デフォルト値の変更:日本語文書では「両端揃え (JustificationValues.Both)」が好まれる場合があります。メソッドのデフォルト引数を Both に変更すると便利です。
- インデントの追加:ParagraphProperties に Indentation オブジェクトを追加することで、字下げ(インデント)も同時に設定可能です。C#
// 左インデントを追加する例 pPr.Append(new Indentation() { Left = "720" }); // 約1.27cm (1440 = 1インチ)
注意点
- プロパティの順序:OpenXMLの仕様上、Paragraph 内の要素順序は厳密ではありませんが、一般的に ParagraphProperties (pPr) は Run よりも先に Paragraph に追加する必要があります。
- Bothの効果:JustificationValues.Both(両端揃え)は、テキストが短すぎて1行に収まる場合は Left と見た目が変わりません。行を折り返すほどの長さがある場合にのみ効果が可視化されます。
- Distribute:JustificationValues.Distribute(均等割り付け)を使用すると、文字数に関わらず行幅いっぱいに文字が配置されますが、見出しなどで使うと文字間隔が極端に広くなることがあるため注意してください。
応用
スタイル付きの見出しを中央揃えにする
見出しスタイルを適用しつつ、中央揃えにする拡張例です。
public void AddCenteredHeading(string text)
{
var p = new Paragraph();
var pPr = new ParagraphProperties();
// スタイルID "Heading1" を指定
pPr.Append(new ParagraphStyleId() { Val = "Heading1" });
// 中央揃えを指定
pPr.Append(new Justification() { Val = JustificationValues.Center });
p.Append(pPr);
p.Append(new Run(new Text(text)));
_body.Append(p);
}
まとめ
OpenXMLで段落の見た目を制御するには、Paragraph の直下に ParagraphProperties を配置し、その中に Justification などの具体的な設定要素を追加するという構造を理解することが重要です。このパターンを覚えれば、配置だけでなく、行間、背景色、境界線なども同様の手順で設定できるようになります。
