跳至页脚内容
使用 IRONWORD

如何在 C# 中不需要 Office Interop 创建 Word 文档

Microsoft Word 文档用途广泛,从正式的商业报告到私人信件均可使用。 在 C# 中,开发人员经常需要以编程方式生成 Microsoft Word 文档。 Windows 应用程序开发人员历来使用 Microsoft Office Interop 和 C# 生成和创建 Word 文档。

然而,这种方法并非人人都能接受,有些开发者使用的操作系统或 Linux 机器上可能没有 Microsoft Office 界面。 在这种情况下,开发人员必须探索其他可以在不同平台上独立运行的库。 IronWordIron Software出品的一个功能强大的库,可用于以编程方式处理 Word 文件。

IronWord 为在 .NET 应用程序中处理 Word 文档提供了强大的功能,并且可以在不同的平台和基于 Linux 的 docker 镜像/容器上运行。 IronWord 具有直观的 C#、VB.NET Word 和 Docx 文档 API,无需安装 Microsoft Office、Office 自动化或 Word Interop 即可构建、编辑和导出 Word 文档文件。 IronWord 完全支持 .NET 8、7、6、Framework、Core 和 Azure。

本文将探讨如何使用 IronWord 库在 C# 中创建 Word 文档。

如何在不使用 Office Interop 的情况下用 C# 创建 Word 文档

  1. 创建一个新的 C# 项目。
  2. 安装IronWord库。
  3. 使用 IronWord 库创建 Word 文档。
  4. 向现有文档添加内容。
  5. 保存创建的 Word 文档。
  6. 打开并显示创建的 Word 文档。

先决条件:

  1. Visual Studio: 确保您已安装Visual Studio或其他C#开发环境。
  2. NuGet包管理器: 确保您可以使用NuGet管理项目中的包。

步骤 1:创建一个新的 C# 项目

创建一个新的 C# 控制台应用程序,或者使用一个现有的项目来生成 Word 文档。

选择控制台应用程序模板并点击下一步。

如何在不使用 Office Interop 的情况下用 C# 创建 Word 文档:图 1 - 用于创建新项目的控制台应用程序模板

在下一步中,您可以提供解决方案和项目名称。

如何在不使用 Office Interop 的情况下用 C# 创建 Word 文档:图 2 - 使用解决方案和项目名称配置项目

选择.NET版本并点击"创建"。

如何在不使用 Office Interop 的情况下用 C# 创建 Word 文档:图 3 - 使用正确的 .NET 版本创建项目

步骤 2:安装 IronWord 库

打开您的 C# 项目,并使用 NuGet 包管理器控制台安装IronWord库:

Install-Package IronWord -Version 2024.1.2

也可以使用 Visual Studio 包管理器安装 NuGet 包,如下所示。

如何在不使用 Office Interop 的情况下用 C# 创建 Word 文档:图 4 - 使用 VS 包管理器安装 IronWord

步骤 3:使用 IronWord 库创建并保存 Word 文档

让我们从使用 IronWord 库创建 Word 文档这个简单的例子开始。 以下代码演示了如何创建一个包含单个段落的 Word 文档,该段落的内容为"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

执行上述代码示例后,将创建新文档文件example.docx ,输出结果如下所示。

如何在 C# 中不使用 Office Interop 创建 Word 文档:图 5 - 通过上述代码创建的 Word 文档。

这是一个使用 IronWord 生成 Word 文档文件的基本示例。 如需了解更多信息,您可以阅读文档

在 Word 文档中添加带样式的段落

现在我们已经知道如何使用 IronWord 创建简单的 Word 文档,接下来让我们添加段落和样式文本。

TextRun 还可以获取样式数据,增强文本的视觉效果。 文本可以设置删除线、粗体、斜体和下划线等样式。

修改以下代码并将其添加到您之前编写的程序中。

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

在 Word 文档中添加表格

为了更清晰地呈现数据,也可以用网格的形式来表示。 当数据以网格形式排列时,就称为表格。 使用 IronWord,我们可以向 Word 文档中添加表格和图像,如下所示:

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

在上面的示例中,我们使用边框向 Word 文档中添加了一个表格。

在 Word 文档中添加图片

图片可以增强文档的呈现效果,并增添更多色彩和视觉吸引力。

可以使用 IronWord 以编程方式将图像添加到 Word 文档中,如下面的代码所示:

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

这里,我们使用IronWord.Models.Image向段落中添加一个高度和宽度均为 200 像素的图像。

许可(提供免费试用)

使用IronWord需要许可证。 从Iron Software网站获取试用密钥。该密钥需要添加到appsettings.json中。

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

提供您的电子邮件以获取试用许可证。 提交您的电子邮件地址后,密钥将通过电子邮件发送给您。

如何在不使用 Office Interop 的情况下用 C# 创建 Word 文档:图 6 - 试用表单成功提交后的弹出窗口

结论

使用IronWord库在 C# 中创建 Word 文档,无需依赖 Microsoft Office,即可灵活高效地生成文档。无论您需要创建简单的信函,还是包含表格和图像的复杂报告,IronWord 都能以编程方式助您轻松实现。 本文提供了创建 Word 文档的全面教程。 借助 IronWord,您可以自动创建 Word 文档,使您的 C# 应用程序更加灵活高效。

对于希望将 PDF 文件操作与生成的 Word 文档结合使用的开发人员来说, IronPDF是 Iron Software 开发的另一个 C# 库,无需再寻觅其他工具。

常见问题解答

如何在C#中不使用Microsoft Office Interop创建Word文档?

您可以通过使用IronWORD库在C#中创建Word文档。该库允许您无需安装Microsoft Office即可编程地生成、编辑和保存Word文档。

使用IronWORD相较于Microsoft Office Interop有哪些优势?

IronWORD提供了在Linux等非Windows平台上运行的灵活性,Microsoft Office Interop在这些平台上不可用。它还消除了对Microsoft Office安装的依赖,从而简化了开发过程。

如何开始使用IronWORD创建Word文档?

要开始使用IronWORD创建Word文档,首先在您的C#项目中通过NuGet包管理器安装IronWORD库。然后,使用IronWORD API以编程方式构建和操作Word文档。

我能否使用IronWORD与最新的.NET版本?

是的,IronWORD兼容各种.NET版本,包括.NET 8, 7, 6, Framework, Core, 和Azure,允许您将其集成到现代C#应用程序中。

如何使用IronWORD向Word文档中添加样式化文本?

IronWORD允许您使用TextRunTextStyle类添加样式化文本。这些类使您能够对文档中的特定文本段应用粗体、斜体和下划线等样式。

使用IronWORD是否可以在Word文档中包含表格?

是的,您可以使用IronWORD在Word文档中包含表格。该库允许您定义具有行和单元格的表格,并可以通过边框和其他样式自定义其外观。

如何使用IronWORD将图像插入到Word文档中?

要将图像插入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 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。