Jak utworzyć dokument programu Word za pomocą języka C#

W tym samouczku nauczymy się jak utworzyć dokument Worda za pomocą C#, napisać tekst z innym formatowaniem czcionki, wstawić do niego hiperłącze i zapisać dokument w formacie pliku DOCX.

Poniższe kroki wyjaśniają, w jaki sposób C# tworzy plik dokumentu programu Word.

Kroki, aby utworzyć dokument programu Word przy użyciu języka C#

  1. Zainstaluj pakiet Aspose.Words for .NET z NuGet
  2. Dodaj odwołanie do przestrzeni nazw Aspose.Words i Aspose.Words.Saving
  3. Utwórz instancję klas Document i DocumentBuilder
  4. Napisz tekst i wstaw hiperłącze do dokumentu
  5. Zapisz dokument w formacie pliku DOCX

Wcześniej sprawdzaliśmy Jak wstawić nagłówek i stopkę w DOCX za pomocą C#. Poniższy przykład kodu w C# generuje dokument programu Word w dobrze znanym formacie pliku DOCX. Możesz użyć tego samego podejścia do tworzenia dokumentów Word w różnych formatach plików, np. DOC, RTF itp., Używając metody Document.Save. Tego przykładowego kodu można użyć, gdy jest zainstalowana platforma .NET.

Kod do generowania dokumentu Word za pomocą 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);
}
}
}

Powyższy przykład kodu w c# tworzy dokument Worda od podstaw. Klasa dokumentu reprezentuje pusty dokument programu Word. Musisz powiązać DocumentBuilder z Document. Możesz użyć DocumentBuilder do wstawiania różnych typów treści do dokumentu Word, np. tabeli, obrazów, tekstu itp.

 Polski