如何使用 C# 创建 Word 文档

在本教程中,我们将学习**如何使用 C# 创建 Word 文档,编写一些具有不同字体格式的文本,在其中插入超链接,并将文档保存为 DOCX 文件格式。

以下步骤说明 C# 如何创建 Word 文档文件

使用 C# 创建 Word 文档的步骤

  1. 从 NuGet 安装 Aspose.Words for .NET
  2. 添加引用 Aspose.Words 和 Aspose.Words.Saving 命名空间
  3. 创建 DocumentDocumentBuilder 类的实例
  4. 写一些文本并将超链接插入到文档中
  5. 将文档保存为 DOCX 文件格式

之前,我们研究了 如何使用 C# 在 DOCX 中插入页眉和页脚C# 中的以下代码示例以众所周知的 DOCX 文件格式生成 Word 文档。 您可以使用相同的方法创建不同文件格式的 Word 文档,例如 DOC、RTF 等,使用 Document.Save 方法。 此代码示例可用于安装 .NET 的地方。

使用 C# 生成 Word 文档的代码

using System.Drawing;
using Aspose.Words;
using Aspose.Words.Saving;
namespace KBCodeExamples
{
class how_to_create_word_document_using_c_sharp
{
public static void Main(string[] args)
{
//Set Aspose license before creating blank Word document
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License();
AsposeWordsLicense.SetLicense(@"Aspose.Words.lic");
// Create a blank Word document
Document doc = new Document();
// Initialize a new instance of DocumentBuilder class
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a string surrounded by a border
builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5d;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;
builder.Write("Text surrounded by green border.");
// Remove all font formatting specified explicitly
builder.Font.ClearFormatting();
builder.InsertBreak(BreakType.ParagraphBreak);
builder.Write("For more information, please visit the ");
// Insert a hyperlink and emphasize it with custom formatting
// The hyperlink will be a clickable piece of text which will take us to the location specified in the URL
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;
builder.InsertHyperlink("Aspose Knowledge Base", "https://kb.aspose.com/", false);
builder.Font.ClearFormatting();
builder.Writeln(".");
OoxmlSaveOptions saveOptions = new OoxmlSaveOptions
{
Compliance = OoxmlCompliance.Iso29500_2008_Strict,
SaveFormat = SaveFormat.Docx
};
// Save the document with strict compliance level
doc.Save("create word document using C#.docx", saveOptions);
}
}
}

c# 中的上述代码示例从头开始创建 Word 文档。 Document 类表示一个空白的 Word 文档。您需要将 DocumentBuilder 与 Document 相关联。 您可以使用 DocumentBuilder 将不同类型的内容插入 Word 文档,例如表格、图像、文本等。

 简体中文