跳至页脚内容
使用 IRONWORD

VS 2022 编程创建新 Word 文档 (教程)

在数字时代,文档正日益数字化。 在商业环境中,文档通常与微软 Word 及其文档型 Word 文件相关联。编写和编辑微软 Word文档已成为大型组织中信息传递的基础。 然而,手动创建和编辑文档可能是一个痛苦的过程; 以编程方式自动生成 Word 文档也不是一件容易的事,因为许多开源库都依赖于 Microsoft Office Word。

然而,管理和创建 Word 文档并不一定非得这么难。 IronWord是一个 C# Word 库,它不依赖于 Microsoft Office Word,允许用户自定义整个文档,同时还允许以编程方式生成文档和创建文档模板。

在今天的教程中,我将简要解释如何使用 IronWord 编程创建 Microsoft Word 文档并提供简短示例。

IronWord:AC# 词库

IronWord 是一款极其可靠且用户友好的 C# Docx 库,它使开发人员能够使用 C# 构建和修改 Word 文档,而无需依赖 Microsoft Office 或 Word Interop 等传统库。此外,它拥有丰富的文档,并全面支持 .NET 8、7、6、.NET Framework、.NET Core 和 Azure,使其与大多数应用程序具有广泛的兼容性。 这种灵活性使其成为您可能遇到的任何应用的绝佳选择。

建立环境

在这个例子中,我们将使用Visual Studio创建一个控制台应用程序,并展示如何创建空白 Word 文档以及如何使用 IronWord 库对其进行操作。 在进行下一步之前,请确保您已安装 Visual Studio。

首先,我们创建一个新的控制台应用程序。

然后,提供项目名称并保存位置,如下所示。

最后,选择所需的框架。

安装 C# Word 库

创建空白控制台应用程序后,我们将通过 NuGet 包管理器下载IronWord

点击"管理 NuGet 程序包",然后在"浏览"选项卡中搜索 IronWord,如下所示。

之后,将其安装到新创建的项目中。

或者,您也可以在命令行中输入以下命令来安装 IronWord。

Install-Package IronWord

现在一切都已准备就绪,让我们来看一个创建 Word 文档的示例。

许可证密钥

请注意,IronWord 需要许可证密钥才能运行。 您可以访问此链接,作为免费试用的一部分获得密钥。

// 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

收到试用密钥后,请在项目中设置此变量。

创建新的 Word 文档

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 以编程方式创建新 Word 文档(教程):图 6 - 上述示例的输出

解释

  1. 首先,我们在示例代码中导入 IronWord 库及其模型。
  2. 我们创建一个新的Text变量。 此变量允许我们向 Word 文档中添加文本。
  3. 然后我们将textRun添加到Paragraph 。 这样我们就可以通过区分两者来轻松地处理文本。
  4. 我们将paragraph参数传递给一个新的WordDocument类,以创建一个新的文档对象。
  5. 最后,我们将文档另存为 Word 文件"document.docx"。

在前面的例子中,我们创建了一个包含基本文本的 Word 文档。 让我们来看一个使用更高级功能的例子,例如自定义文本和添加文本效果。

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 以编程方式创建新 Word 文档(教程):图 7 - 上述示例代码的输出

代码解释

  1. 与上面的示例一样,我们创建Text对象并添加文档的示例文本。
  2. 然后我们创建一个新的TextStyle对象,并将IsItalic属性设置为true ,表示文本应为斜体。
  3. 我们对boldText变量执行相同的操作,将IsBold属性赋值为true
  4. 然后我们将TextStyle变量分配给它们各自的Text变量。
  5. 我们创建一个Paragraph变量,并调用AddText方法来添加斜体和粗体文本。
  6. 我们使用AddParagraph方法将段落添加到文档中。
  7. 最后,我们将文档保存为"save_document.docx"。

以上示例展示了开发人员可以使用 IronWord 的字体和样式。 除了斜体和粗体文本效果外,IronWord 还提供其他功能,以确保开发人员在各种情况下都能创建独特的 Word 文档。

结论

! VS 2022 以编程方式创建新 Word 文档(教程):图 8 - IronWord 许可信息

我们的演示表明,使用IronWord库以 C# 编程方式创建 Word 文档是多么容易。 该库的灵活性和可扩展性使其成为开发人员在实际场景中(例如在 Word 文档中自定义文本、字体和样式)的宝贵工具。 了解 Word 如何与其他应用程序集成,可以为开发人员提供应对挑战的更多解决方案。

IronWord 提供免费试用许可证

常见问题解答

如何在C#中通过编程方式创建Microsoft Word文档?

您可以通过使用IronWord库在C#中通过编程方式创建Microsoft Word文档。初始化一个WordDocument对象,添加必要的内容,使用SaveAs方法将其导出为.docx文件。

使用IronWord与Microsoft Office Interop相比创建Word文档有什么好处?

IronWord提供了无需安装Microsoft Office的好处,提供了更大的灵活性和更容易进行不同平台之间的集成,不依赖于Office。

如何在Visual Studio中安装IronWord?

要在Visual Studio中安装IronWord,打开NuGet包管理器,搜索IronWord,并将其安装到项目中。或者,使用命令行Install-Package IronWord

我可以使用IronWord格式化Word文档中的文本吗?

是的,您可以使用IronWord通过利用TextStyle对象对文本元素应用诸如斜体和粗体的各种样式来格式化Word文档中的文本。

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创建Paragraph对象,将文本添加到其中,并将其包含在WordDocument中,以编程方式向Word文档添加段落。

Jordi Bardia
软件工程师
Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 利用这些技能时,他就在游戏编程。分享产品测试、产品开发和研究的责任,Jordi 在持续的产品改进中增加了巨大的价值。多样的经验使他面临挑战并保持投入,他表示这是在 Iron Software 工作的最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。