跳過到頁腳內容
使用 IRONWORD

VS 2022 程式化創建新 Word 文件(教程)

Documents are increasingly becoming digital in the digital age. Documents in the business setting are often associated with Microsoft Word and its document-based Word file. Writing and editing Microsoft Word documents has become the foundation for passing information around in large organizations. However, manually creating and editing documents can be a painful process; to automate Word generation programmatically is no easy feat either, as many open-source libraries rely on Microsoft Office Word for dependency.

However, managing and creating Word documents doesn't need to be this difficult. IronWord is a C# Word Library that is not dependent on Microsoft Office Word and allows users to customize the entire document while also allowing document generation and creating document templates programmatically.

In today's tutorial, I'll briefly explain how to programmatically create a Microsoft Word Document using IronWord and provide brief examples.

IronWord: A C# Word Library

IronWord is an exceptionally reliable and user-friendly C# Docx library that empowers developers to construct and modify Word documents using C#, all without needing traditional dependencies such as Microsoft Office or Word Interop. Additionally, it boasts extensive documentation and provides full support for .NET 8, 7, 6, Framework, Core, and Azure, making it universally compatible with most applications. This level of flexibility makes it an excellent choice for any application you may be dealing with.

Setting up the environment

For this example, we'll create a console app using Visual Studio and showcase how to create blank Word documents and manipulate them using the IronWord Library. Before we proceed with this next step, ensure that you have Visual Studio installed.

First, let's create a new console app.

Then, provide a project name and save the location, as shown below.

Finally, select the desired framework.

Installing the C# Word Library

After creating the blank console app, we'll download IronWord through NuGet Package Manager.

Click on "Manage NuGet Packages," then search IronWord in the "Browse" tab as shown below.

Afterward, install it onto the newly created project.

Alternatively, you can type the following command in the command line to install IronWord.

Install-Package IronWord

Now that everything is set up and ready to go, let's move to an example of creating Word documents.

License Key

Please remember that IronWord requires a licensing key for operation. You can get a key as part of a free trial by visiting this link.

// Replace the license key variable with the trial key you obtained
IronWord.License.LicenseKey = "REPLACE-WITH-YOUR-KEY";
// Replace the license key variable with the trial key you obtained
IronWord.License.LicenseKey = "REPLACE-WITH-YOUR-KEY";
' Replace the license key variable with the trial key you obtained
IronWord.License.LicenseKey = "REPLACE-WITH-YOUR-KEY"
$vbLabelText   $csharpLabel

After receiving a trial key, set this variable in your project.

Creating a new Word Document

using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Create a textrun
        Text textRun = new Text("Sample text");
        Paragraph paragraph = new Paragraph();
        paragraph.AddChild(textRun);

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

        // Export docx
        doc.SaveAs("document.docx");
    }
}
using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Create a textrun
        Text textRun = new Text("Sample text");
        Paragraph paragraph = new Paragraph();
        paragraph.AddChild(textRun);

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

        // Export docx
        doc.SaveAs("document.docx");
    }
}
Imports IronWord
Imports IronWord.Models

Friend Class Program
	Shared Sub Main()
		' Create a textrun
		Dim textRun As New Text("Sample text")
		Dim paragraph As New Paragraph()
		paragraph.AddChild(textRun)

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

		' Export docx
		doc.SaveAs("document.docx")
	End Sub
End Class
$vbLabelText   $csharpLabel

VS 2022 Programmatically Create New Word Documents (Tutorial): Figure 6 - Output from the example above

Explanation

  1. First, we import the IronWord Library and its models in the sample code.
  2. We create a new Text variable. This variable allows us to add text to the Word document.
  3. We then add the textRun to a Paragraph. This allows us to easily manipulate the text by distinguishing between the two.
  4. We pass the paragraph parameter to a new WordDocument class to create a new document object.
  5. Finally, we save the document as "document.docx" to a Word file.

In the previous example, we created a Word document with basic text. Let's do an example with more advanced features, such as customizing the text and adding text effects.

using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Ensure to set up the license key
        IronWord.License.LicenseKey = "YOUR-KEY";

        // Load an existing docx
        WordDocument doc = new WordDocument("document.docx");

        // Create sample texts with styles
        Text introText = new Text("This is an example paragraph with italic and bold styling.");
        TextStyle italicStyle = new TextStyle()
        {
            IsItalic = true
        };
        Text italicText = new Text("Italic example sentence.");
        italicText.Style = italicStyle;

        TextStyle boldStyle = new TextStyle()
        {
            IsBold = true
        };
        Text boldText = new Text("Bold example sentence.");
        boldText.Style = boldStyle;

        // Create a paragraph and add texts
        Paragraph paragraph = new Paragraph();
        paragraph.AddText(introText);
        paragraph.AddText(italicText);
        paragraph.AddText(boldText);

        // Add paragraph to the document
        doc.AddParagraph(paragraph);

        // Export the document
        doc.SaveAs("save_document.docx");
    }
}
using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Ensure to set up the license key
        IronWord.License.LicenseKey = "YOUR-KEY";

        // Load an existing docx
        WordDocument doc = new WordDocument("document.docx");

        // Create sample texts with styles
        Text introText = new Text("This is an example paragraph with italic and bold styling.");
        TextStyle italicStyle = new TextStyle()
        {
            IsItalic = true
        };
        Text italicText = new Text("Italic example sentence.");
        italicText.Style = italicStyle;

        TextStyle boldStyle = new TextStyle()
        {
            IsBold = true
        };
        Text boldText = new Text("Bold example sentence.");
        boldText.Style = boldStyle;

        // Create a paragraph and add texts
        Paragraph paragraph = new Paragraph();
        paragraph.AddText(introText);
        paragraph.AddText(italicText);
        paragraph.AddText(boldText);

        // Add paragraph to the document
        doc.AddParagraph(paragraph);

        // Export the document
        doc.SaveAs("save_document.docx");
    }
}
Imports IronWord
Imports IronWord.Models

Friend Class Program
	Shared Sub Main()
		' Ensure to set up the license key
		IronWord.License.LicenseKey = "YOUR-KEY"

		' Load an existing docx
		Dim doc As New WordDocument("document.docx")

		' Create sample texts with styles
		Dim introText As New Text("This is an example paragraph with italic and bold styling.")
		Dim italicStyle As New TextStyle() With {.IsItalic = True}
		Dim italicText As New Text("Italic example sentence.")
		italicText.Style = italicStyle

		Dim boldStyle As New TextStyle() With {.IsBold = True}
		Dim boldText As New Text("Bold example sentence.")
		boldText.Style = boldStyle

		' Create a paragraph and add texts
		Dim paragraph As New Paragraph()
		paragraph.AddText(introText)
		paragraph.AddText(italicText)
		paragraph.AddText(boldText)

		' Add paragraph to the document
		doc.AddParagraph(paragraph)

		' Export the document
		doc.SaveAs("save_document.docx")
	End Sub
End Class
$vbLabelText   $csharpLabel

VS 2022 Programmatically Create New Word Documents (Tutorial): Figure 7 - Output from the example code above

Explanation of code

  1. Like the example above, we create the Text object and add the sample text for the document.
  2. We then create a new TextStyle object and assign the property IsItalic as true, indicating the text should be in italics.
  3. We do the same for the boldText variable, assigning true to the property IsBold.
  4. We then assign the TextStyle variables to their respective Text variables.
  5. We create a Paragraph variable and call the AddText method to add the italic and bold text.
  6. We add the paragraph to the document using the AddParagraph method.
  7. Finally, we save the document as "save_document.docx".

The example above showcases the fonts and styles developers can use using IronWord. Aside from italics and bold text effects, IronWord also offers other features to ensure developers have all the options to create unique Word documents in various scenarios.

Conclusion

VS 2022 Programmatically Create New Word Documents (Tutorial): Figure 8 - IronWord licensing information

Our demonstrations showed how easy it is to use the IronWord library to create Word documents in C# programmatically. The library's flexibility and scalability make it a valuable tool for developers in real-life scenarios, such as customizing text, font, and style in a Word document. Understanding how Word integrates with other applications provides developers additional solutions to their challenges.

IronWord provides a free trial license.

常見問題解答

我如何在 C# 中程式化創建 Microsoft Word 文件?

您可以使用 IronWord 庫在 C# 中程式化創建 Microsoft Word 文件。初始化一個 WordDocument 對象,添加必要的內容,並使用 SaveAs 方法將其導出為 .docx 文件。

為什麼使用 IronWord 比使用 Microsoft Office Interop 創建 Word 文件更好?

IronWord 提供比 Microsoft Office Interop 更多的好處,因為它不需要安裝 Microsoft Office ,提高了靈活性,並且可以在不同平台上更容易集成而無需依賴 Office。

如何在 Visual Studio 中安裝 IronWord?

要在 Visual Studio 中安裝 IronWord,打開 NuGet 包管理器,搜尋 IronWord,並將其安裝到您的專案中。或者,利用命令行使用 Install-Package IronWord

我可以使用 IronWord 格式化 Word 文件中的文本嗎?

是的,您可以使用 IronWord 格式化 Word 文檔中的文本,使用 TextStyle 對象將斜體和粗體等樣式應用到文本元素。

IronWord 與 .NET 和 Azure 相容嗎?

是的,IronWord 完全相容於 .NET 8, 7, 6, Framework, Core 和 Azure,使其能夠用於各種應用。

如何解決 IronWord 的安裝問題?

如果您遇到 IronWord 的安裝問題,請確保您使用的是兼容的 Visual Studio 和 .NET 版本,並且您的 NuGet 包管理器已更新。檢查網絡連接並重試安裝過程。

開始使用 IronWord 創建 Word 文件需要什麼?

要開始使用 IronWord 創建 Word 文件,請將 IronWord 庫和其模型導入到您的 C# 專案中。然後,初始化一個 WordDocument 物件來開始構建您的文件。

如何使用 IronWord 程式化添加段落到 Word 文件中?

您可以使用 IronWord 程式化地將段落添加到 Word 文件中,方法是創建 Paragraph 對象,將文本添加到其中,並將其包含到 WordDocument 中。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。