有些人使用 Microsoft Office Interop 库来创建 Word 文档,但是他们经常问如何在没有互操作的情况下在 C# 中创建 Word 文档的问题。这就是 Aspose.Words for .NET 发挥作用的地方,可以帮助您轻松地在 C# 中创建 Word 文档。
下面的步骤连同 C# 代码示例一起回答了这个问题。这表明您可以在 .NET 应用程序中轻松高效地创建 DOCX 或 DOC 文件,无论是 .NET 控制台实用程序、Windows 应用程序还是 ASP.NET Web 项目。 Aspose.Words 可与每一种 .NET 平台技术无缝协作。
在没有自动化的情况下在 C# 中创建 Word 文档的步骤
- 使用 Aspose.Words for .NET NuGet 包
- 添加对 Aspose.Words namespace 的引用
- 使用 SetLicense 方法申请 Aspose 许可证
- 创建一个新的 Document Class 实例
- 创建一个 DocumentBuilder Class 对象并在构造函数中传递 Document 对象
- 设置 DocumentBuilder 对象的必需属性
- 将输出 Word 文档另存为文件或流
在没有自动化的情况下在 C# 中创建 Word 文档的代码
using System; | |
//Add reference to Aspose.Words for .NET API | |
//Use following namespaces to Word Document generator code | |
using Aspose.Words; | |
namespace CreateWordDocumentWithoutInterop | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before creating Word document without Interop | |
//using Aspose.Words for .NET | |
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License(); | |
AsposeWordsLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//Create an instance of Document class of Aspose.Words for .NET | |
//This initiates a blank Word document | |
Document WordDocumentWithoutInterop = new Document(); | |
//An instance of DocumentBuilder class is used to add | |
//content to the Word Document | |
DocumentBuilder WordDocumentBuilder = new DocumentBuilder(WordDocumentWithoutInterop); | |
//Add some text with bold formatting | |
WordDocumentBuilder.Bold = true; | |
WordDocumentBuilder.Writeln("We're adding this line of text in the word document using DocumentBuilder Class"); | |
WordDocumentBuilder.Writeln("This does not require Office Interop or Office Automation"); | |
//Finally, save the generated word document to docx format | |
WordDocumentWithoutInterop.Save("Word_Document_Created_Without_Interop_using_CSharp.docx"); | |
} | |
} | |
} |
在这个 C# 代码示例中,我们创建了一个只有两行文本的简单 Word document,并将粗体属性应用于文本。但是,您可以通过添加表格、单元格和 Word Document Object Model (DOM) 的其他不同对象来做更多的事情并扩展上述代码。
要执行 Aspose.Words for .NET API 的上述 C# 代码,您无需在计算机或将安装应用程序的服务器上安装 Microsoft Word。这使得创建word文档变得更加容易和快捷。