相互運用機能なしでC#でWord文書を作成する方法

Microsoft Office相互運用機能ライブラリを使用してWord文書を作成する人もいますが、相互運用機能を使用せずにC#でWord文書を作成する方法について質問することがよくあります。ここでAspose.Words for .NETが機能し、C#でWord文書を簡単に作成できるようになります。

この質問は、C#コードサンプルとともに以下の手順で回答されています。これは、.NETコンソールユーティリティ、Windowsアプリケーション、ASP.NET Webプロジェクトなど、.NETアプリケーションでDOCXまたはDOCファイルを最初から簡単かつ効率的に作成できることを示しています。 Aspose.Wordsは、すべての.NETプラットフォームテクノロジとシームレスに連携します。

自動化せずにC#でWord文書を作成する手順

  1. Aspose.Words for .NETNuGetパッケージを使用する
  2. Aspose.Words namespaceへの参照を追加します
  3. SetLicenseメソッドを使用してAsposeライセンスを適用します
  4. 新しいDocument Classインスタンスを作成します
  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#コードの例では、2行のテキストだけで単純なWord documentを作成し、テキストに太字の属性を適用しました。ただし、テーブル、セル、およびWord Document Object Model (DOM)の他のさまざまなオブジェクトを追加することで、さらに多くのことを実行し、上記のコードを拡張できます。

Aspose.Words for .NET APIの上記のC#コードを実行するために、コンピューターまたはアプリケーションがインストールされるサーバーにMicrosoftWordをインストールする必要はありません。これにより、Word文書の作成がはるかに簡単かつ迅速になります。

 日本語