跳過到頁腳內容
使用 IRONWORD

如何在 C# 中創建 Word 文檔

Microsoft Word files are widely used for document creation and editing, making them a fundamental part of many business applications. In C# development, the ability to generate and manipulate MS Word documents programmatically is crucial. One powerful tool for achieving this is the IronWord library, which provides a comprehensive set of features for working with Word files in C#.

Microsoft also provides a developer tutorial to automate Microsoft Word Documents using Visual C#. In this article, we are going to explore how to create a Word Document in C# using IronWord - a powerful C# Word Document Library.

How to Create Word Documents in C#

  1. Create a C# project in Visual Studio
  2. Install IronWord Library
  3. Create a WordDocument object
  4. Add content using the AddText method
  5. Add the text Paragraph to the WordDocument object
  6. Save to DOCX File using the SaveAs method

IronWord Library

IronWord webpage

The IronWord library is a robust C# DOCX library developed by Iron Software. It offers an intuitive API for building, editing, and exporting Word documents without the need to install Microsoft Office or Word Interop. With support for various .NET versions and platforms, IronWord simplifies the process of working with Word files in different environments.

IronWord works even without installing the Word app. Microsoft Word Interop is not required to create a Word Doc.

Features of IronWord

Cross-Platform Support

IronWord is designed to run on C#, F#, and VB.NET, supporting .NET 8, 7, 6, 5, Core, Standard, or Framework. It is versatile enough to be utilized in web, mobile, desktop, and console applications.

Document Structure Manipulation

IronWord provides a rich set of features for manipulating document structure, including reading and editing Word files. Developers can extract text and images, edit page setup, set custom margins, and add paragraphs, text runs, images, shapes, and tables.

Styling and Formatting

The library allows developers to set styling for various elements, such as font family and size, color, bold, italic, strikethrough, underline, superscript, and subscript. Additionally, it supports the customization of alignments, background color, and bullet/numbering lists.

Cross-Platform Compatibility

IronWord is compatible with various operating systems, including Windows, Linux, macOS, iOS, and Android, making it a versatile solution for a wide range of applications.

Setting Up the Environment

To begin, open Visual Studio, and you'll see the welcome screen.

1. Create a New .NET Framework Console Application

Click on "Create a new project." Search for "Console App (.NET Framework)," select it from the list, and click "Next." Name your project and click "Create." Visual Studio will set up a new .NET Framework console application with a basic template, including a Main method as the entry point.

Configuring the project name and location

2. Install IronWord Using the NuGet Package Manager

In Visual Studio, navigate to the "Tools" menu, select "NuGet Package Manager," and then "Manage NuGet Packages for Solution." In the NuGet window, go to the "Browse" tab, type "IronWord" in the search box, and hit enter. Select the package from the results, ensure your console application project is checked on the right, and click "Install." This will add the necessary references for using IronWord within your C# application. Now you’re ready to begin creating Word documents with IronWord.

Installing IronWord with the NuGet Package Manager

Using Package Manager Console:

Run the following command in the Package Manager Console:

Install-Package IronWord

Steps to Create a Word Document

Now that IronWord is installed, you can use the library to create a Word document.

  1. Importing IronWord Namespace:
using IronWord;
using IronWord.Models;
using IronWord;
using IronWord.Models;
Imports IronWord
Imports IronWord.Models
$vbLabelText   $csharpLabel

These lines import the IronWord and IronWord.Models namespaces, allowing you to use classes and functionalities from the IronWord library in your C# code.

  1. Creating a Word Document Instance:
WordDocument doc = new WordDocument();
WordDocument doc = new WordDocument();
Dim doc As New WordDocument()
$vbLabelText   $csharpLabel

Here, a new instance of the WordDocument class is created. This represents an empty Word document that you can start adding content to.

  1. Adding Content to the Document: The following sample code adds text to the document object:
doc.AddText("Add text using IronWord");
doc.AddText("Add text using IronWord");
doc.AddText("Add text using IronWord")
$vbLabelText   $csharpLabel

This line adds a paragraph to the Word document with the text "Add text using IronWord". The AddText method is a convenient way to insert textual content into the document.

  1. Saving the Document:
doc.SaveAs("output.docx");
doc.SaveAs("output.docx");
doc.SaveAs("output.docx")
$vbLabelText   $csharpLabel

After adding content to the document, you use the SaveAs method to save the Word document to a file. In this case, it saves the document with the filename "output.docx" in the project directory.

The above steps will create a new Word document, add a paragraph with text, and save the document with the specified filename.

Here's the complete source code:

using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Create a new Word document
        WordDocument doc = new WordDocument();

        // Add text to the document
        doc.AddText("Add text using IronWord");

        // Save the document to a file
        doc.SaveAs("output.docx");
    }
}
using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Create a new Word document
        WordDocument doc = new WordDocument();

        // Add text to the document
        doc.AddText("Add text using IronWord");

        // Save the document to a file
        doc.SaveAs("output.docx");
    }
}
Imports IronWord
Imports IronWord.Models

Friend Class Program
	Shared Sub Main()
		' Create a new Word document
		Dim doc As New WordDocument()

		' Add text to the document
		doc.AddText("Add text using IronWord")

		' Save the document to a file
		doc.SaveAs("output.docx")
	End Sub
End Class
$vbLabelText   $csharpLabel

Overall, this code demonstrates the basic steps to create a Word document using the IronWord library. You instantiate a WordDocument object, add content to it (in this case, a simple paragraph), and then save the document to a file. That's it! Document created successfully.

This is a straightforward example, and you can extend it to include more complex document structures, formatting, and additional content based on your application's requirements.

For more code examples on how to create, read, and edit existing Word documents, please visit this code examples page.

Output

Upon running the program, a Word document named "output.docx" will be generated in the project directory. You can open this document to see the added content.

Outputted PDF from the previous code

Conclusion

In this article, we explored the significance of creating Microsoft Word files in C# applications and introduced the IronWord library as a powerful solution for working with Word documents. We covered its features, the process of setting up a C# console project in Visual Studio, and steps to install and utilize IronWord to create Word documents. With IronWord, developers can seamlessly integrate Word document generation capabilities into their C# applications, enhancing their document processing capabilities.

For more detailed information about IronWord and its capabilities, please visit its official documentation page.

IronWord is free for development purposes and can be licensed for commercial use. However, it also offers a free trial to test out its complete functionality in commercial mode before making a decision.

常見問題解答

我如何在 C# 中生成 Word 文檔?

你可以使用 IronWord 庫在 C# 中生成 Word 文檔。首先在 Visual Studio 中設置一個 C# 項目,通過 NuGet 包管理器安裝 IronWord,創建一個 WordDocument 實例,使用 AddText 之類的方法添加內容,並使用 SaveAs 方法保存文檔。

IronWord 庫在生成 Word 文檔方面提供了哪些好處?

IronWord 提供多個好處,包括跨平台支持、文檔結構操作以及樣式和格式設置選項。它允許開發者在不需要 Microsoft Word 或 Word Interop 的情況下處理 Word 文檔。

我可以在 Linux 上使用 IronWord 進行文檔操作嗎?

是的,IronWord 支持包括 Linux 在內的多個平台,允許在不同操作系統上進行 Word 文檔的操作,而不需要 Microsoft Word。

使用 C# 向 Word 文檔添加文本需要哪些步驟?

要使用 IronWord 向 Word 文檔添加文本,請創建一個 WordDocument 實例並使用 AddText 方法將文本插入到文檔中。 最後,使用 SaveAs 方法保存你的更改。

使用 IronWord 可以在 Word 文檔中設置文本樣式嗎?

是的,IronWord 允許你在 Word 文檔中設置和格式化文本。 你可以自定義字體、大小、顏色,並以編程方式應用其他格式選項。

IronWord 如何協助文檔結構的操作?

IronWord 提供了文檔結構操作的功能,使開發者能夠處理段落、文本運行、圖像、形狀和表格,以及管理頁面設置和自定義邊距。

使用 IronWord 需要在我的機器上安裝 Microsoft Word 嗎?

不,你不需要在你的機器上安裝 Microsoft Word 即可使用 IronWord。該庫獨立於 Microsoft Word 和 Word Interop 運行。

IronWord 可以在移動應用開發中使用嗎?

是的,IronWord 支持在 iOS 和 Android 等移動平台上的開發,使其在跨平台應用開發中具有多樣性。

使用 IronWord 創建的 Word 文檔保存的過程是什麼?

創建並修改你的 WordDocument 實例後,使用 SaveAs 方法將文檔保存到文件中,指定所需的文件名和位置。

我在哪裡可以找到更多關於使用 IronWord 庫的教程?

欲了解更多關於使用 IronWord 的詳細教程和代碼示例,你可以參考其網站上的官方 IronWord 文檔。

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