Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i generate a word document docx with existing text as in a template, but fill in value thru a asp.net web form?

I want to generate a word document (.docx) file, which is based on a template could be a word template or that the text can be stored in code.

Now the document generated should be based on the Input provided by the user using an ASP.net Web Form with Text Boxes to input the values.

These values will be taken in and placed in placeholder positions in the word template.

  1. How can i use a word template in an ASP.net web project?
  2. How can i take the values from the ASP.net webform and pass it to the word template, fill in the placeholder with the text and then generate the word document?

I have seen some examples where the text to be generated is created as HTML and then the file exported is given filetype msword to save as a word file. But in this case i wonder, how can i give page numbers and other header or footer values to the generated document.

So if i can use a word template, to just fill in the values the user wants and then generate the final document, then that's great.

Is there anything new to do this in Visual Studio 2012? I am trying to do this using C#.

like image 530
Cristus Cleetus Avatar asked Aug 04 '13 18:08

Cristus Cleetus


2 Answers

You have several options for creating word documents -

  1. Use word automation - this is using Ms Word directly. Not recommended if you're running on a server - it's slow and suffers from extensibility and other issues.

  2. Use OpenXML - this is Microsoft's SDK to work with Office 2007+ file formats. There are several ways to accomplish your goal with OpenXML - like using bookmarks or content controls. Look at this SO question - How to replace content in template docx document and Open XML SDK 2.0 (Aug 09)? or this one - How to create *.docx files from a template in C# or google it (while not that difficult, the entire solution is more that a few lines of code and does require a bit of understanding)

  3. Use third party tools or controls - I'm not really familiar with them.

like image 187
Vadim Avatar answered Nov 05 '22 16:11

Vadim


You can create your template by creating a Word document ( including logos, header, footer, etc), putting the placeholders and save it as "Word 2003 xml" document.

Next, you can read the template.xml as a text file, replace the placeholders with the values, and response the entire string as a content type "application/msword"

The placeholder could be {MY_PLACEHOLDER1}

Before creating the template, you must deactivate ( in Word ) all related with Ortography, because the "bad ortography" highlightings are stored as a part of the xml document, and {MY_PLACEHOLDER1} can be stored as MY_PLACEHOLDER1 (the "{" and "}" characters are stored separated with their own word xml tags )

Regards,

like image 20
Javier Campo Avatar answered Nov 05 '22 14:11

Javier Campo