このチュートリアルでは、** C#を使用してWordドキュメントを作成する方法**、さまざまなフォント形式でテキストを記述し、ハイパーリンクを挿入して、ドキュメントをDOCXファイル形式で保存する方法を学習します。
次の手順では、* C#でWord文書ファイル*を作成する方法について説明します。
C#を使用してWord文書を作成する手順
- NuGetからAspose.Words for .NETパッケージをインストールします
- 参照Aspose.WordsおよびAspose.Words.Saving名前空間を追加します
- DocumentクラスとDocumentBuilderクラスのインスタンスを作成します
- テキストを書いて、ドキュメントにハイパーリンクを挿入します
- ドキュメントをDOCXファイル形式で保存します
以前、C#を使用してDOCXにヘッダーとフッターを挿入する方法を調べました。 ** C#の次のコード例は、よく知られているDOCXファイル形式でWord文書**を生成します。 同じアプローチを使用して、Document.Saveメソッドを使用してDOC、RTFなどのさまざまなファイル形式でWord文書を作成できます。 このコード例は、.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文書を最初から作成します。 ドキュメントクラスは、空白のWordドキュメントを表します。 DocumentBuilderをDocumentに関連付ける必要があります。 DocumentBuilderを使用して、テーブル、画像、テキストなど、さまざまな種類のコンテンツをWord文書に挿入できます。