Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8988693
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T22:03:55+00:00 2026-06-15T22:03:55+00:00

TL;DR Can I generate Word documents with .NET like XAML ItemTemplates? I’m finding it

  • 0

TL;DR Can I generate Word documents with .NET like XAML ItemTemplates?

I’m finding it pretty hard to come up with a solution that meets all my requirements, so I thought I’ll throw this out to stackoverflow in the hope someone can guide me. Much thanks in advance.

Simply put, I need to generate Word document based on data from a database.

My ideal solution: I want it to work like how DataTemplates work in xaml. I’ve found heaps of examples and solutions where the Template represents a static document, with bits of (single) dynamic content which needs to be replaced.

e.g. WordDocGenerator

The thing is, I need a solution where I can specify a template for each level of the hierarchy, and the document generator will use these item level templates to build a final document based on a Document level template.

My specific requirements are:

  • Preferably .NET solution
  • No need for office to be installed on the server
  • A template exists that encapsulates purely the ‘View’ of the document (doesn’t necessarily have to be a Word template) which a user can modify at will (within boundaries of course). This is very important, as the user needs to control the presentation by just modifying the Word template directly.
  • Preferably at each level of data hierarchy there will be an accompanying template.
  • Headers and footers
  • Table of Contents

Let’s say the data hierarchy is like this

class Country
{
  public string Name { get; set; }
  public IList<City> { get; set; }
}

class City
{
  public string Name { get; set; }
  public IList<Suburb> { get; set;}
}

class Suburb
{
  public string Name { get; set; }
  public int Postcode { get; set; }
}

In my mind the solution will be a function call, which accepts a list of countries.

// returns path to generated document
public static string GenerateDocument(IList<Country> countries);

This function will accept the list of countries, and for each country

  • use a prepared template for Countries to present the country data.
  • for each City in country, use prepared template for Cities to present the City data inside the Country template
  • for each Suburb in city, use prepared template for Suburbs to present the Suburb data inside the City template.

Finally, these generated document ‘pieces’ will be accumulated into one final Word Document using a Document level template, which will specify the Title page, headers/footers, TOC.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T22:03:56+00:00Added an answer on June 15, 2026 at 10:03 pm

    I eventually got what I wanted. I did everything manually, with a lot of help from Eric White’s articles.

    So a taste of the source is this. Have a template ensuring the first three paragraphs are the 3 levels of hierarchy you want. Loop through your collections, clone the node, replace the text, repeat.

    private const string COUNTRY_TITLE = "[[CountryTitle]]"
    private const string CITY_TITLE = "[[CityTitle]]"
    private const string SUBURB_TITLE = "[[SuburbTitle]]"
    
    using (WordprocessingDocument myDoc = WordprocessingDocument.Open(outputPath, true))
    {
        var mainPart = myDoc.MainDocumentPart;
        var body = mainPart.Document.Body;
    
        var originalCountryPara = body.ElementAt(0);
        var originalCityPara = body.ElementAt(1);
        var originalSuburbPara = body.ElementAt(2); 
    
        foreach (var country in Countries)
        {
            if (!String.IsNullOrEmpty(country.Title))
            {
                // clone Country level node on template
                var clonedCountry = originalCountryPara.CloneNode(true);
    
                // replace Country title
                Helpers.CompletelyReplaceText(clonedCountry as Paragraph, COUNTRY_TITLE,  country.Title);
                body.AppendChild(clonedCountry);
            }    
    
            foreach (var city in country.Cities)
            {
                if (!String.IsNullOrEmpty(city.Title))
                {
                    // clone City level node on template
                    var clonedCity = originalCityPara.CloneNode(true);
    
                    // replace City title
                    Helpers.CompletelyReplaceText(clonedCity as Paragraph, CITY_TITLE, city.Title);
                    body.AppendChild(clonedCity);
                }
    
                foreach (var suburb in city.Suburbs)
                {
                    // clone Suburb level node on template
                    var clonedSuburb = originalSuburbPara.CloneNode(true);
    
                    // replace Suburb title
                    Helpers.CompletelyReplaceText(clonedSuburb as Paragraph, SUBURB_TITLE, suburb.Title);
                    body.AppendChild(clonedSuburb);         
                }
            }
        }
    
        body.RemoveChild(originalCountryPara);
        body.RemoveChild(originalCityPara);
        body.RemoveChild(originalSuburbPara);
    
        mainPart.Document.Save();
    }
    
    /// <summary>
    /// 'Completely' refers to the fact this method replaces the whole paragraph with newText if it finds
    /// existingText in this paragraph. The only thing spared is the pPr (paragraph properties)
    /// </summary>
    /// <param name="paragraph"></param>
    /// <param name="existingText"></param>
    /// <param name="newText"></param>
    public static void CompletelyReplaceText(Paragraph paragraph, string existingText, string newText)
    {
        StringBuilder stringBuilder = new StringBuilder();            
        foreach (var text in paragraph.Elements<Run>().SelectMany(run => run.Elements<Text>()))
        {                
            stringBuilder.Append(text.Text);
        }
    
        string paraText = stringBuilder.ToString();
        if (!paraText.Contains(existingText)) return;
    
        // remove everything here except properties node                
        foreach (var element in paragraph.Elements().ToList().Where(element => !(element is ParagraphProperties)))
        {
            paragraph.RemoveChild(element);
        }
    
        // insert new run with text
        var newRun = new Run();
        var newTextNode = new Text(newText);
        newRun.AppendChild(newTextNode);
        paragraph.AppendChild(newRun);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The purpose is to generate proposal documents that can manually be edited in Word
I'm working on a project where I can generate Word documents, one of the
I'm looking for some tool that can generate many document formats like Microsoft Excel,
I'm trying to use PHPWord to generate word documents. And the document can be
How can we generate javadoc as a word document instead of the traditional html
ASP.NET MVC 3 can generate scaffold code for us(controllers and views). The generated views
ASP.NET MVC can generate HTML elements using HTML Helpers, for example @Html.ActionLink() , @Html.BeginForm()
Does anyone know a C# framework that can generate public/private keys, X.509 certificates and
I'm wondering if i can generate a scaffold without getting that annyoing s after
I am actually using the library DocX to generate Word document (2007+) from .Net.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.