Kako stvoriti Word dokument koristeći C#

U ovom vodiču naučit ćemo kako stvoriti Word dokument koristeći C#, napisati neki tekst s različitim formatiranjem fonta, umetnuti hipervezu u njega i spremiti dokument u DOCX format datoteke.

Sljedeći koraci objašnjavaju kako C# stvara datoteku Word dokumenta.

Koraci za stvaranje Word dokumenta pomoću C#

  1. Instalirajte Aspose.Words for .NET paket iz NuGeta
  2. Dodajte referencu Aspose.Words i Aspose.Words.Spremanje imenskih prostora
  3. Napravite primjerak klasa Document i DocumentBuilder
  4. Napišite tekst i umetnite hipervezu u dokument
  5. Spremite dokument u DOCX format datoteke

Prethodno smo pogledali Kako umetnuti zaglavlje i podnožje u DOCX koristeći C#. Sljedeći primjer koda u C# generira Word dokument u dobro poznatom DOCX formatu datoteke. Možete koristiti isti pristup za stvaranje Word dokumenta u različitim formatima datoteka, npr. DOC, RTF, itd. koristeći metodu Document.Save. Ovaj primjer koda može se koristiti tamo gdje je instaliran .NET.

Kod za generiranje Word dokumenta pomoću 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);
}
}
}

Gornji primjer koda u c# kreira Word dokument od nule. Klasa dokumenta predstavlja prazan Word dokument. Morate povezati DocumentBuilder s Documentom. Možete koristiti DocumentBuilder za umetanje različitih vrsta sadržaja u Word dokument, npr. tablice, slike, tekst itd.

 Hrvatski