Як створити документ Word за допомогою C#

У цьому підручнику ми дізнаємося, як створити документ Word за допомогою C#, написати текст із іншим форматуванням шрифту, вставити в нього гіперпосилання та зберегти документ у форматі DOCX.

Наступні кроки пояснюють, як C# створює файл документа Word.

Кроки для створення документа Word за допомогою C#

  1. Установіть пакет Aspose.Words for .NET із NuGet
  2. Додайте посилання на простори імен Aspose.Words і Aspose.Words.Saving
  3. Створіть екземпляр класів Document і DocumentBuilder
  4. Напишіть текст і вставте гіперпосилання в документ
  5. Збережіть документ у форматі DOCX

Раніше ми розглядали Як вставити верхній і нижній колонтитули в DOCX за допомогою C#. Наступний приклад коду в C# створює документ Word у відомому форматі файлу DOCX. Ви можете використовувати той самий підхід для створення документа Word у різних форматах файлів, наприклад DOC, RTF тощо, використовуючи метод Document.Save. Цей приклад коду можна використовувати там, де встановлено .NET.

Код для створення документа Word за допомогою C#

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 з нуля. Клас Document представляє порожній документ Word. Вам потрібно пов’язати DocumentBuilder із Document. Ви можете використовувати DocumentBuilder, щоб вставляти різні типи вмісту в документ Word, наприклад таблицю, зображення, текст тощо.

 Українська