企業向けアプリケーションにおいて、Word 文書(DOC/DOCX)は依然として情報共有やレポート作成の中心ツールです。契約書、通知、報告書、さらには自動生成されるレポートなど、さまざまな場面で Word 文書のプログラムによる生成が必要です。従来の方法では、開発者は手動操作や Office 自動化(Interop)に依存することがありましたが、これらは Office のインストール依存、パフォーマンスの低さ、エラーの発生しやすさといった問題があります。
本記事では、Free Spire.Doc for .NET を使って C# で Word 文書を作成し、テキスト、表、画像、ヘッダー・フッターを挿入する方法、および異なる形式や MemoryStream に保存する方法について詳しく解説します。例示データは理解を容易にするため英語テキストを使用しています。
1. Spire.Doc のインストール
使用前に、NuGet から Spire.Doc をインストールします。
Install-Package FreeSpire.Doc
インストール完了後、C# プロジェクトで必要な名前空間を参照します。
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.IO;
using System.Drawing;
2. Word 文書の作成と段落の追加
// 新しい文書を作成
Document document = new Document();
Section section = document.AddSection();
// タイトル段落を追加
Paragraph title = section.AddParagraph();
title.AppendText("Employee Report");
title.Format.HorizontalAlignment = HorizontalAlignment.Center;
title.ApplyStyle(BuiltinStyle.Heading1);
// 本文段落を追加
Paragraph intro = section.AddParagraph();
intro.AppendText("This report contains the details of employees in the company. All information is for internal use only.");
intro.Format.HorizontalAlignment = HorizontalAlignment.Left;
intro.Format.LineSpacing = 15f;
ポイント:
-
AddSectionで独立したセクションを作成し、ページ分割やスタイル管理を容易にします。 - 内蔵スタイル(
BuiltinStyle)で Word 標準の書式を適用可能です。 -
Paragraph.Formatで段落の揃え、行間、インデントなどを自由に設定できます。
3. 表の挿入とデータ入力
// 5 行 5 列の表を作成(タイトル行含む)
Table table = section.AddTable(true);
table.ResetCells(5, 5);
// タイトル行を設定
table[0, 0].AddParagraph().AppendText("EmployeeID");
table[0, 1].AddParagraph().AppendText("FullName");
table[0, 2].AddParagraph().AppendText("Department");
table[0, 3].AddParagraph().AppendText("HireDate");
table[0, 4].AddParagraph().AppendText("Salary");
// サンプルデータを入力
table[1, 0].AddParagraph().AppendText("E101");
table[1, 1].AddParagraph().AppendText("John Miller");
table[1, 2].AddParagraph().AppendText("Finance");
table[1, 3].AddParagraph().AppendText("2020-02-15");
table[1, 4].AddParagraph().AppendText("7500");
table[2, 0].AddParagraph().AppendText("E102");
table[2, 1].AddParagraph().AppendText("Sarah Brown");
table[2, 2].AddParagraph().AppendText("HR");
table[2, 3].AddParagraph().AppendText("2019-07-10");
table[2, 4].AddParagraph().AppendText("6800");
table[3, 0].AddParagraph().AppendText("E103");
table[3, 1].AddParagraph().AppendText("Mike Smith");
table[3, 2].AddParagraph().AppendText("IT");
table[3, 3].AddParagraph().AppendText("2020-01-20");
table[3, 4].AddParagraph().AppendText("9000");
table[4, 0].AddParagraph().AppendText("E104");
table[4, 1].AddParagraph().AppendText("Lisa Jones");
table[4, 2].AddParagraph().AppendText("Marketing");
table[4, 3].AddParagraph().AppendText("2018-09-05");
table[4, 4].AddParagraph().AppendText("5500");
ポイント:
-
AddTable(true)でデフォルトスタイル付きの表を作成。 -
ResetCellsで行列数を指定。 -
table[i, j].AddParagraph()でテキストやハイパーリンクを挿入可能。
4. 表のスタイルと段落書式のカスタマイズ
// タイトル行の背景色設定
for (int i = 0; i < 5; i++)
{
table[0, i].CellFormat.BackColor = Color.LightGray;
table[0, i].Paragraphs[0].GetStyle().CharacterFormat.Bold = true;
}
// 表の枠線設定
table.TableFormat.Borders.BorderType = BorderStyle.Single;
// 行の高さ設定
for (int i = 0; i < table.Rows.Count; i++)
{
table.Rows[i].Height = 20f;
}
5. 画像の挿入
// 画像を追加
Paragraph imgPara = section.AddParagraph();
DocPicture picture = imgPara.AppendPicture(Image.FromFile("company_logo.png"));
picture.Width = 100;
picture.Height = 50;
imgPara.Format.HorizontalAlignment = HorizontalAlignment.Right;
ポイント:
-
AppendPictureで画像を挿入し、幅や高さを調整可能。 - 段落内に配置し、左・中央・右に揃えられます。
6. ヘッダーとフッターの追加
// ヘッダー
HeaderFooter header = section.HeadersFooters.Header;
Paragraph headerPara = header.AddParagraph();
headerPara.AppendText("Company Confidential");
headerPara.Format.HorizontalAlignment = HorizontalAlignment.Center;
// フッター
HeaderFooter footer = section.HeadersFooters.Footer;
Paragraph footerPara = footer.AddParagraph();
footerPara.AppendText("Page ");
footerPara.AppendField("PAGE", FieldType.FieldPage);
footerPara.AppendText(" of ");
footerPara.AppendField("NUMPAGES", FieldType.FieldNumPages);
footerPara.Format.HorizontalAlignment = HorizontalAlignment.Center;
ポイント:
- ヘッダー・フッターにはテキスト、ページ番号、画像などを挿入可能。
-
FieldType.FieldPageとFieldType.FieldNumPagesで自動ページ番号を生成できます。
7. Word 文書およびその他形式への保存
// DOCX 形式で保存
document.SaveToFile("EmployeeReport.docx", FileFormat.Docx);
// PDF 形式で保存
document.SaveToFile("EmployeeReport.pdf", FileFormat.PDF);
// HTML 形式で保存
document.SaveToFile("EmployeeReport.html", FileFormat.Html);
// MemoryStream への保存
using (MemoryStream ms = new MemoryStream())
{
document.SaveToStream(ms, FileFormat.Docx);
// クライアントに送信したり、データベースに保存可能
}
8. 作成結果の例
上記のコードで生成された Word 文書の例:
9. 応用シナリオ
-
自動レポート生成
システムで定期的に社員レポートや販売レポートを生成し、手作業を削減。 -
動的コンテンツ生成
データベースに基づき、段落・表・画像を動的に埋め込み、テンプレート文書を生成。 -
多形式エクスポート
Spire.Doc は DOCX、PDF、HTML など複数形式に対応し、印刷・Web 表示・二次処理に対応可能。 -
Web 連携
MemoryStream を利用すれば、文書をサーバー上で直接生成しクライアントに送信可能で、ディスク保存不要。
10. まとめ
本記事では Spire.Doc for .NET を使用して、以下を実現しました:
- Word 文書を作成し、タイトル・本文・表を追加
- 表や段落のスタイルを整える
- 画像やヘッダー・フッターを挿入
- DOCX、PDF、HTML など複数形式で保存
- MemoryStream に保存してネットワーク送信や二次処理に利用
Document、Section、Paragraph、Table、DocPicture などのコアクラスとメソッドを使いこなすことで、Word 文書の自動生成を簡単に実現でき、業務システムの開発効率や文書管理のレベルを向上させることができます。
