如何在没有互操作的情况下在 C# 中创建 Word 文档?

230 篇文章 2 订阅
196 篇文章 7 订阅

有些人使用 Microsoft Office Interop 库来创建 Word 文档,但是他们经常问如何在没有互操作的情况下在 C# 中创建 Word 文档的问题。这就是Aspose.Words for .NET发挥作用的地方,可以帮助轻松地在 C# 中创建 Word 文档。

下面的步骤和 C# 代码示例一起回答了这个问题。这表明可以在 .NET 应用程序(无论是 .NET 控制台实用程序、Windows 应用程序还是 ASP.NET Web 项目)中从头开始创建DOCX或DOC文件是多么容易和高效。Aspose.Words 无缝地与每种 .NET 平台技术配合使用。

Aspose.Words for .NET是高级Word文档处理API,用于执行各种文档管理和操作任务。该API支持生成,修改,转换,呈现和打印文档的能力,而无需在跨平台应用程序中直接利用Microsoft Word。(下载Aspose.Words安装包

在没有自动化的情况下在 C# 中创建 Word 文档的步骤

  1. 使用Aspose.Words for .NET NuGet 包
  2. 添加对Aspose.Words 命名空间的引用
  3. 使用 SetLicense 方法申请 Aspose 许可证
  4. 创建一个新的文档类实例
  5. 创建一个DocumentBuilder Class对象并在构造函数中传递 Document 对象
  6. 设置 DocumentBuilder 对象的必需属性
  7. 将输出的 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 文档,并将粗体属性应用于文本。但是,可以通过添加表格、单元格和Word 文档对象模型 (DOM) 的其他不同对象来执行更多操作并扩展上述代码。

要执行 Aspose.Words for .NET API 的上述 C# 代码,您不需要在您的计算机或将安装应用程序的服务器上安装 Microsoft Word。这使得创建 Word 文档变得更加容易和快捷。

如果您发现任何其他关于在没有互操作的情况下在 c# 中创建 word 文档的问题,可加入Aspose资源分享交流群(761297826)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值