フッターコンテンツにスキップ
IRONWORDの使用方法

Office Interopを使用せずにC#でワード文書を作成する方法

Microsoft Word documents are widely used for various purposes, from formal business reports to personal letters. In C#, developers often need to generate Microsoft Word documents programmatically. Windows application developers have traditionally used the Microsoft Office Interop to generate and create Word documents using C#.

However, this approach isn't accessible to everyone, and developers can be found using an OS or on a Linux machine where the Microsoft Office interface isn't available. In these cases, developers must explore other libraries that can independently work on different platforms. One such powerful library for working with Word files programmatically is IronWord, from Iron Software.

IronWord provides robust functionality for working with Word documents in .NET applications and can run on different platforms and docker images/containers based on Linux. With IronWord, which has intuitive C#, VB.NET Word, and Docx Document API, there is no need to install Microsoft Office, Office automation, or Word Interop, to build, edit, and export Word document files. IronWord fully supports .NET 8, 7, 6, Framework, Core, and Azure.

This article will explore the creation of Word documents in C# using the IronWord library.

How to Create Word Documents Without Office Interop in C#

  1. Create a new C# project.
  2. Install the IronWord library.
  3. Create a Word document using the IronWord library.
  4. Add content to the now existing document.
  5. Save the created Word document.
  6. Open and display the created Word document.

Prerequisites:

  1. Visual Studio: Ensure you have Visual Studio or any other C# development environment installed.
  2. NuGet Package Manager: Make sure you can use NuGet to manage packages in your project.

Step 1: Create a New C# Project

Create a new C# console application or use an existing project where you want to generate the Word document.

Select the console application template and click next.

How to Create Word Documents Without Office Interop in C#: Figure 1 - Console App template for creating a new project

In the next step, you can provide the solution and project names.

How to Create Word Documents Without Office Interop in C#: Figure 2 - Configuring project with solution and project name

Select the .NET Version and click "Create".

How to Create Word Documents Without Office Interop in C#: Figure 3 - Creating project with correct .NET version

Step 2: Install the IronWord Library

Open your C# project and install the IronWord library using the NuGet Package Manager Console:

Install-Package IronWord -Version 2024.1.2

The NuGet package can also be installed using Visual Studio Package Manager, as shown below.

How to Create Word Documents Without Office Interop in C#: Figure 4 - Installing IronWord with the VS package manager

Step 3: Create and Save a Word Document using the IronWord Library

Let's start with the simple example of creating a Word document using the IronWord library. The following code demonstrates how to create an essential Word document with a single paragraph containing the text "Hello, World!"

using IronWord;
using IronWord.Models;

// Create a text run instance with "Hello, World!" content
TextRun textRun = new TextRun("Hello, World!");

// Create a paragraph and add the text run to it
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Create a new Word document object with the paragraph
WordDocument doc = new WordDocument(paragraph);

// Save the document as a .docx file
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
using IronWord;
using IronWord.Models;

// Create a text run instance with "Hello, World!" content
TextRun textRun = new TextRun("Hello, World!");

// Create a paragraph and add the text run to it
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Create a new Word document object with the paragraph
WordDocument doc = new WordDocument(paragraph);

// Save the document as a .docx file
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
Imports IronWord
Imports IronWord.Models

' Create a text run instance with "Hello, World!" content
Private textRun As New TextRun("Hello, World!")

' Create a paragraph and add the text run to it
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)

' Create a new Word document object with the paragraph
Dim doc As New WordDocument(paragraph)

' Save the document as a .docx file
doc.SaveAs("example.docx") ' Saves the file to disk with the name example.docx
$vbLabelText   $csharpLabel

After executing the above code example, the new document file, example.docx, is created and the output is as shown below.

How to Create Word Documents Without Office Interop in C#: Figure 5 - Word document created through the code above.

This is a fundamental example of generating a Word document file using IronWord. For more information, you can read the Documentation.

Adding Paragraphs with Style to a Word Document

Now that we know how to create a simple Word document using IronWord, let's add paragraphs and styled text.

TextRun can also take style data, enhancing the text's visual representation. Text can be set with styles such as strikethrough, bold, italic, and underline.

Modify and add the code below to the program you have made previously.

using IronWord;
using IronWord.Models;

// Create text runs with different styles
TextRun textRun = new TextRun("Hello, World!"); // Simple string
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Configure and add italic text
TextRun introText = new TextRun("This is an example paragraph with italic and bold styling.");
TextStyle italicStyle = new TextStyle()
{
    IsItalic = true
};
TextRun italicText = new TextRun("Italic example sentence.", italicStyle);

// Configure and add bold text
TextStyle boldStyle = new TextStyle()
{
    IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);

// Add text runs to the paragraph
paragraph.AddTextRun(introText);
paragraph.AddTextRun(italicText);
paragraph.AddTextRun(boldText);

// Create and save the new Word document
WordDocument doc = new WordDocument(paragraph);
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
using IronWord;
using IronWord.Models;

// Create text runs with different styles
TextRun textRun = new TextRun("Hello, World!"); // Simple string
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Configure and add italic text
TextRun introText = new TextRun("This is an example paragraph with italic and bold styling.");
TextStyle italicStyle = new TextStyle()
{
    IsItalic = true
};
TextRun italicText = new TextRun("Italic example sentence.", italicStyle);

// Configure and add bold text
TextStyle boldStyle = new TextStyle()
{
    IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);

// Add text runs to the paragraph
paragraph.AddTextRun(introText);
paragraph.AddTextRun(italicText);
paragraph.AddTextRun(boldText);

// Create and save the new Word document
WordDocument doc = new WordDocument(paragraph);
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
Imports IronWord
Imports IronWord.Models

' Create text runs with different styles
Private textRun As New TextRun("Hello, World!") ' Simple string
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)

' Configure and add italic text
Dim introText As New TextRun("This is an example paragraph with italic and bold styling.")
Dim italicStyle As New TextStyle() With {.IsItalic = True}
Dim italicText As New TextRun("Italic example sentence.", italicStyle)

' Configure and add bold text
Dim boldStyle As New TextStyle() With {.IsBold = True}
Dim boldText As New TextRun("Bold example sentence.", boldStyle)

' Add text runs to the paragraph
paragraph.AddTextRun(introText)
paragraph.AddTextRun(italicText)
paragraph.AddTextRun(boldText)

' Create and save the new Word document
Dim doc As New WordDocument(paragraph)
doc.SaveAs("example.docx") ' Saves the file to disk with the name example.docx
$vbLabelText   $csharpLabel

Adding a Table to a Word Document

For clear representation of data, it can also be represented in a grid. When data is arranged as a grid, it is called a table. Using IronWord, we can add tables and images to the Word document as shown below:

using IronWord;
using IronWord.Models;

// Create a table cell with sample text
TableCell cell = new TableCell();
TextRun textRun = new TextRun("Sample text");

// Add text run to the cell as a paragraph
cell.AddContent(new Paragraph(textRun));

// Configure cell border style
BorderStyle borderStyle = new BorderStyle
{
    BorderColor = new IronColor(IronSoftware.Drawing.Color.Black),
    BorderValue = IronWord.Models.Enums.BorderValues.Thick,
    BorderSize = 5
};

// Set table borders
TableBorders tableBorders = new TableBorders
{
    TopBorder = borderStyle,
    RightBorder = borderStyle,
    BottomBorder = borderStyle,
    LeftBorder = borderStyle
};
cell.Borders = tableBorders;

// Create a table row and add cells to it
TableRow row = new TableRow();
row.AddCell(cell); // Add the first cell
row.AddCell(cell); // Add the second cell, duplicating to mimic a row with two identical cells

// Create a table and add the row to the table
Table table = new Table();
table.AddRow(row);

// Create and save a Word document using the table
WordDocument doc = new WordDocument(table);
doc.SaveAs("Document.docx"); // Saves the file to disk with the name Document.docx
using IronWord;
using IronWord.Models;

// Create a table cell with sample text
TableCell cell = new TableCell();
TextRun textRun = new TextRun("Sample text");

// Add text run to the cell as a paragraph
cell.AddContent(new Paragraph(textRun));

// Configure cell border style
BorderStyle borderStyle = new BorderStyle
{
    BorderColor = new IronColor(IronSoftware.Drawing.Color.Black),
    BorderValue = IronWord.Models.Enums.BorderValues.Thick,
    BorderSize = 5
};

// Set table borders
TableBorders tableBorders = new TableBorders
{
    TopBorder = borderStyle,
    RightBorder = borderStyle,
    BottomBorder = borderStyle,
    LeftBorder = borderStyle
};
cell.Borders = tableBorders;

// Create a table row and add cells to it
TableRow row = new TableRow();
row.AddCell(cell); // Add the first cell
row.AddCell(cell); // Add the second cell, duplicating to mimic a row with two identical cells

// Create a table and add the row to the table
Table table = new Table();
table.AddRow(row);

// Create and save a Word document using the table
WordDocument doc = new WordDocument(table);
doc.SaveAs("Document.docx"); // Saves the file to disk with the name Document.docx
Imports IronWord
Imports IronWord.Models

' Create a table cell with sample text
Private cell As New TableCell()
Private textRun As New TextRun("Sample text")

' Add text run to the cell as a paragraph
cell.AddContent(New Paragraph(textRun))

' Configure cell border style
Dim borderStyle As New BorderStyle With {
	.BorderColor = New IronColor(IronSoftware.Drawing.Color.Black),
	.BorderValue = IronWord.Models.Enums.BorderValues.Thick,
	.BorderSize = 5
}

' Set table borders
Dim tableBorders As New TableBorders With {
	.TopBorder = borderStyle,
	.RightBorder = borderStyle,
	.BottomBorder = borderStyle,
	.LeftBorder = borderStyle
}
cell.Borders = tableBorders

' Create a table row and add cells to it
Dim row As New TableRow()
row.AddCell(cell) ' Add the first cell
row.AddCell(cell) ' Add the second cell, duplicating to mimic a row with two identical cells

' Create a table and add the row to the table
Dim table As New Table()
table.AddRow(row)

' Create and save a Word document using the table
Dim doc As New WordDocument(table)
doc.SaveAs("Document.docx") ' Saves the file to disk with the name Document.docx
$vbLabelText   $csharpLabel

In the example above, we added a table to a Word document using borders.

Adding Images to a Word Document

Images enhance the document's presentation and can add more colors and visual appeal.

Images can be added programmatically to a Word document using IronWord as shown in the code below:

using IronWord;
using IronWord.Models;

// Load a new document
WordDocument doc = new WordDocument();

// Configure and add image to the document
IronWord.Models.Image image = new IronWord.Models.Image("SalesChart.jpg")
{
    Width = 200, // Set image width in pixels
    Height = 200 // Set image height in pixels
};
Paragraph paragraph = new Paragraph();
paragraph.AddImage(image); // Add image to paragraph
doc.AddParagraph(paragraph); // Add paragraph to the document

// Save the document as a .docx file
doc.SaveAs("save_document.docx"); // Saves the file to disk with the name save_document.docx
using IronWord;
using IronWord.Models;

// Load a new document
WordDocument doc = new WordDocument();

// Configure and add image to the document
IronWord.Models.Image image = new IronWord.Models.Image("SalesChart.jpg")
{
    Width = 200, // Set image width in pixels
    Height = 200 // Set image height in pixels
};
Paragraph paragraph = new Paragraph();
paragraph.AddImage(image); // Add image to paragraph
doc.AddParagraph(paragraph); // Add paragraph to the document

// Save the document as a .docx file
doc.SaveAs("save_document.docx"); // Saves the file to disk with the name save_document.docx
Imports IronWord
Imports IronWord.Models

' Load a new document
Private doc As New WordDocument()

' Configure and add image to the document
Private image As New IronWord.Models.Image("SalesChart.jpg") With {
	.Width = 200,
	.Height = 200
}
Private paragraph As New Paragraph()
paragraph.AddImage(image) ' Add image to paragraph
doc.AddParagraph(paragraph) ' Add paragraph to the document

' Save the document as a .docx file
doc.SaveAs("save_document.docx") ' Saves the file to disk with the name save_document.docx
$vbLabelText   $csharpLabel

Here, we are adding an image using IronWord.Models.Image with a Height and Width of 200 pixels to a paragraph.

Licensing (Free Trial Available)

IronWord requires a license to use. Obtain a trial key from the Iron Software website. This key needs to be placed in appsettings.json.

{
    "IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}

Provide your email to get a trial license. After you submit your email ID, the key will be delivered via email.

How to Create Word Documents Without Office Interop in C#: Figure 6 - Popup upon a successfully submitted trial form

Conclusion

Creating Word documents in C# using the IronWord library provides a flexible and efficient way to generate documents without relying on Microsoft Office. Whether you need to create simple letters or complex reports with tables and images, IronWord allows you to achieve this programmatically. This article provides a comprehensive tutorial on creating Word documents. With IronWord, you have the power to automate the creation of Word documents, making your C# applications more versatile and productive.

And for developers looking for PDF file manipulation to work in conjunction with their generated Word documents, look no further than IronPDF, another C# library produced by Iron Software.

よくある質問

Microsoft Office Interopを使わずにC#でWordドキュメントを作成するにはどうすればよいですか?

Microsoft Office Interopを使用せずにC#でWordドキュメントを作成するには、IronWORDライブラリを活用します。このライブラリを使用すれば、Microsoft Officeをインストールする必要なく、プログラム内でWordドキュメントを生成し、編集し、保存できます。

Microsoft Office InteropよりIronWORDを使用する利点は何ですか?

IronWORDはLinuxなどのMicrosoft Office Interopが使用できない非Windowsプラットフォームで動作する柔軟性を提供します。また、Microsoft Officeのインストール依存を排除し、開発プロセスを簡素化します。

IronWORDを使用してWordドキュメントの作成を始めるにはどうすればよいですか?

IronWORDを使用してWordドキュメントの作成を始めるには、まずC#プロジェクトでNuGetパッケージマネージャーを使用してIronWORDライブラリをインストールします。その後、IronWORD APIを使ってプログラム的にWordドキュメントを構築し操作します。

IronWORDは最新の.NETバージョンと互換性がありますか?

はい、IronWORDは.NET 8、7、6、Framework、Core、Azureなどのさまざまな.NETバージョンと互換性があります。これにより、現代的なC#アプリケーションに統合することができます。

IronWORDでWordドキュメントにスタイル付きテキストを追加するにはどうすればよいですか?

IronWORDは、TextRunTextStyleクラスを使用してスタイル付きテキストを追加できます。これらのクラスを使用して、Wordドキュメント内の特定のテキストセグメントに太字、イタリック、下線などのスタイルを適用することができます。

IronWORDを使用してWordドキュメントに表を含めることは可能ですか?

はい、IronWORDを使用してWordドキュメントに表を含めることができます。このライブラリでは、行やセルを持つ表を定義でき、境界線や他のスタイルで外観をカスタマイズできます。

IronWORDを使用してWordドキュメントに画像を挿入するにはどうすればよいですか?

IronWORDを使用してWordドキュメントに画像を挿入するには、IronWord.Models.Imageクラスを使って指定された寸法で画像を段落に埋め込むことができ、ドキュメントの視覚的なコンテンツを強化します。

IronWORDの評価用トライアルバージョンはありますか?

はい、Iron SoftwareはIronWORDの無料トライアルを提供しています。これを利用して、購入前にライブラリの機能と能力を評価することができます。

Iron Softwareは他にどのような文書操作ライブラリを提供していますか?

IronWORDに加えて、Iron SoftwareはPDFファイルを操作するためのIronPDFを提供しています。これらのライブラリが揃うことで、C#アプリケーションにおけるWordおよびPDF文書の取り扱いに対する包括的なソリューションを提供します。

Jordi Bardia
ソフトウェアエンジニア
Jordiは、最も得意な言語がPython、C#、C++であり、Iron Softwareでそのスキルを発揮していない時は、ゲームプログラミングをしています。製品テスト、製品開発、研究の責任を分担し、Jordiは継続的な製品改善において多大な価値を追加しています。この多様な経験は彼を挑戦させ続け、興味を持たせており、Iron Softwareで働くことの好きな側面の一つだと言います。Jordiはフロリダ州マイアミで育ち、フロリダ大学でコンピュータサイエンスと統計学を学びました。