Generate a Word Document from a Template

View as MarkdownMarkdown

Set up your AI agent

Give your coding agent live access to the GroupDocs documentation and API reference through the GroupDocs Docs MCP server — no install, no API key. Learn more

claude mcp add --transport http groupdocs-docs https://docs.groupdocs.com/mcp

Also process documents locally

The GroupDocs.Assembly MCP server lets your agent work with files on your machine; they are never uploaded. It needs the .NET 10 SDK or Docker.

claude mcp add groupdocs-assembly -- dnx GroupDocs.Assembly.Mcp --yes
Folders, licensing and more →

The shortest complete path from data to a document: a template somebody edits in Word, a data source of your choosing, and one call. No Microsoft Office on the server, no Open XML by hand, and the layout stays with the people who own the report.

Note
A runnable implementation of this page is on GitHub: word-report-from-template-net.

Step 1: a template

A tag is <<[expression]>>. The expression is evaluated against a data source that you name yourself, and a format may follow the closing bracket:

Order <<[order.Number]>> for <<[order.Customer]>>
Placed on <<[order.Placed]:"dd MMMM yyyy">>

<<foreach [line in order.Lines]>><<[line.Product]>> x<<[line.Quantity]>> - <<[line.Total]:"0.00">> EUR
<</foreach>>
Total: <<[order.Lines.Sum(l => l.Total)]:"0.00">> EUR

Three things are worth noticing. foreach repeats the text between its tags once per element. LINQ is available inside the expressions — Sum, Where, GroupBy, OrderBy — so a total is part of the template rather than of your code. And a format after the bracket, not inside it: <<[order.Placed]:"dd MMMM yyyy">>.

The same tags work in a .docx, where they sit in the paragraphs, tables and headers of a document your colleagues style in Word. See template syntax for the full set.

Step 2: an object

Order order = new Order
{
    Number = 4117,
    Customer = "Quayside Bistro",
    Placed = new DateTime(2026, 11, 3),
    Lines = new List<OrderLine>
    {
        new OrderLine { Product = "Espresso beans, 1 kg", Quantity = 6, Price = 18.40m },
        new OrderLine { Product = "Oat milk, 1 l", Quantity = 24, Price = 1.95m }
    }
};

DocumentAssembler assembler = new DocumentAssembler();
assembler.AssembleDocument(
    Path.Combine(TemplatesPath, "order-confirmation.txt"),
    Path.Combine(OutputPath, "order-confirmation.txt"),
    new DataSourceInfo(order, "order"));

"order" is the name the template uses. Any public property of the object — and any computed property, such as Total => Quantity * Price — is reachable from an expression.

Warning
A data source object must be of a visible type: a public class, not an anonymous type or a private nested class. Anonymous types have no stable member names at runtime and are rejected.

Step 3: a JSON file, and the same template

assembler.AssembleDocument(
    Path.Combine(TemplatesPath, "Customer orders.docx"),
    Path.Combine(OutputPath, "customer-orders.docx"),
    new DataSourceInfo(new JsonDataSource(Path.Combine(DataSourcesPath, "Customers.json")), "customers"));

The template did not change when the data moved from objects to a file. Since 26.11 a template written for typed objects works over JSON, XML and CSV as well: members of dates and numbers that may be missing, Booleans usable as conditions and in predicates, $id/$ref references, and grouping over nested objects.

Other data sources follow the same shape — see a database, XML and JSON.

Step 4: another output format

assembler.AssembleDocument(
    Path.Combine(TemplatesPath, "Customer orders.docx"),
    Path.Combine(OutputPath, "customer-orders.pdf"),
    new LoadSaveOptions(FileFormat.Pdf),
    new DataSourceInfo(new JsonDataSource(Path.Combine(DataSourcesPath, "Customers.json")), "customers"));

The output format is a load-save option, not a different API. DOCX, PDF, ODT, HTML, Markdown and plain text come out of the same call; the list is on Supported document formats.

Where this usually goes next

You needRead
The data has holesTemplates for incomplete data
A spreadsheet instead of a documentExcel reports from a template
A deckPresentations from JSON
To serve this from a web applicationReports in ASP.NET Core
To run it on LinuxDocker and serverless

Is this mail merge?

It replaces it. Classic mail merge fills MERGEFIELD placeholders from one flat row of data: one record, a fixed set of fields, no logic. A GroupDocs.Assembly template adds <<foreach>> for repeating sections, <<if>> for conditions, expressions such as Sum, GroupBy and OrderBy, and nested objects — so an invoice with a variable number of lines and a conditional block is a single template rather than a template plus code.

Frequently asked questions

How do you generate a Word document from a template in C#? Put <<[...]>> tags in a .docx and call DocumentAssembler.AssembleDocument with the template, an output path and a DataSourceInfo holding your data.

Is Microsoft Word or Office needed on the server? No. GroupDocs.Assembly reads and writes the formats itself, on Windows and on Linux.

Can the data be JSON instead of a .NET object? Yes. JsonDataSource takes a file, a stream or a string, and the template does not change.

Can the same template produce a PDF? Yes — add new LoadSaveOptions(FileFormat.Pdf) to the call.

Which template formats are supported? DOCX, DOC, DOCM, DOTX, RTF, ODT and plain text, plus spreadsheet, presentation and e-mail templates with the same tag syntax.