How to generate a word document docx from existing document template

Create your docx document ad add to it some Custom Property.

Click File Tab > Info > Properties > Advanced Property
01-advancedprop

Then navigate to Custom tab and insert your property.
newprop

Next you have to add the Field to the document text
Insert > Quick Parts > Fields
insertquick
or press CTRL + F9

Then Select from “Field names” list the value DocProperty and select your custom property created before.
quick-parts

Ok now we are ready to generate our document.

Create a new Project and add the reference to “docx” package:
http://docx.codeplex.com/

Here my sample

private void button2_Click(object sender, EventArgs e)
{
    DocX g_document;

    g_document = FillTemplate(DocX.Load(@"test.docx"));

    var destinationFile = "testFilled.docx";
    // Save all changes made to this template as Invoice_The_Happy_Builder.docx (We don't want to replace InvoiceTemplate.docx).
    g_document.SaveAs(destinationFile);
    Process.Start(destinationFile);
}

private DocX FillTemplate(DocX template)
{
    template.AddCustomProperty(new CustomProperty("First_Name", "Andrea"));
    template.AddCustomProperty(new CustomProperty("Last_Name", "Regoli"));
    template.AddCustomProperty(new CustomProperty("site", "http://www.andrearegoli.it"));

    return template;
}

You can download the full code here:
http://www.andrearegoli.it/BlogData/Download/GenerateDocument/docxSample.zip

For a full great sample go to docx version 1.0.0.7

http://docx.codeplex.com/releases/view/31554

and download Advance – Invoice Example
also available here:
http://www.andrearegoli.it/BlogData/Download/GenerateDocument/InvoiceExample.zip

Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in .Net, c# e contrassegnata con , . Contrassegna il permalink.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...