reading and modifying placeholders Word document .docx template from MVC application RRS feed

  • Question

  • User1617707200 posted

    I have a requirement in my project where I want to programmatically replace placeholders in a predefined document template with actual values from database. data to replace could be of text or image type. (Note: Project is a web app developed in ASP.NET MVC, .Net framework with EntityFramework for backend operations in VS 2019).

    Scenario is: I have a survey form designed with some questionnaire. User fills the survey form and once complete, he needs to generate a report out of the survey information filled in. for the report format there is a predefined document template(.docx) file available with all styling and formatting applied. Now I want to read this template, search for the placeholders and replace it with appropriate data. It should also repeat the document sections multiple times if required dynamically for multiple categories. It should repeat template contents for those many categories by replacing placeholders with respective category data. while doing this it should not remove or disturb the report styling and format.

    What is the best and simplest way to achieve this? I don't want to use any third party tools. I did some R&D on google and tried few options. But as I red many links, answers/suggestions on Google, it looks like there are many ways to do it but nothing is helping in giving me a complete and proper solution as per my requirement. Do I need to generate the report out of the template as a new document? if so then how do I retain the style and formatting of the template in the new generated report document?

    Thursday, May 14, 2020 5:39 PM

All replies

  • User-474980206 posted

    you will need a library to read and write word documents. If you do not want a 3rd party, your best choice is open xml:




    and thread on using mergefield:



    Thursday, May 14, 2020 6:02 PM
  • User1617707200 posted

    Thanks bruce. Links you shared helped me to some extent. Basic code works fine But it is failing while searching the placeholders in the document. The Template I am using is a custom template and there are multiple placeholders in it at random line no or page. Placeholders can be replaced by either by Text value or Image(s). When I am trying to search placeholder in FieldCode collection, it returns 0. I tried searching it in Run, SdtRun, Text and Paragraph collections but Search always returns false and it never replaces the placeholder.
    Is there any other way to search placeholders in document with OpenXML, irrespective of the collection or element the placeholder is placed? like using Stream object.. but I don't want to loose or disturb the document style and formatting while replacing the values


    Friday, May 15, 2020 8:55 AM