C#でWordファイル(.docx)を作成・編集する方法を2つ紹介します。
1. OpenXMLを使用する方法(おすすめ)
OpenXML は、Wordがインストールされていなくても動作し、簡単に操作できるライブラリです。
Install-Package DocumentFormat.OpenXml
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;
class Program
{
static void Main()
{
string filePath = "output.docx";
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
{
var mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
var body = new Body();
var para = new Paragraph(new Run(new Text("Hello, Word!")));
body.Append(para);
mainPart.Document.Append(body);
mainPart.Document.Save();
}
Console.WriteLine("Wordファイルを作成しました: " + filePath);
}
}
2. Interopを使用する方法(Wordのインストールが必要)
Microsoft.Office.Interop.Word を使用してWordファイルを作成する方法ですが、Wordのインストールが必要です。
Install-Package Microsoft.Office.Interop.Word
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void Main()
{
var wordApp = new Word.Application();
var document = wordApp.Documents.Add();
document.Content.Text = "Hello, Word!";
document.SaveAs2("output.docx");
document.Close();
wordApp.Quit();
Console.WriteLine("Wordファイルを作成しました。");
}
}
使用環境に応じて最適な方法を選んでくださいね!