如何在沒有互操作的情況下在 C# 中創建 Word 文檔?

有些人使用 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)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章