MS Word mailmerge like functionality to allow export to Word document from ASP.Net Web application

StackOverflow https://stackoverflow.com/questions/3181340

  •  02-10-2019
  •  | 
  •  

Question

I have requirement where I need to allow users to upload a Word document with place holders for certain fields which can be found in the database. This will be their template. For example the place holders might be prepended with @@ or something. For example

Dear @@Title @@Lastname

They then can grab a record and hit export to Word document. This will then let them choose the template. They can select the template and then click continue. I will then get the template and replace the @@Title with the title field in the database for the selected record. I am not sure where to start or what components I need to do this.

From my initial investigation it seems that I can do this with the new open XML standard for Office 2007. So perhaps I should read in the template and save all the contents to a db table somewhere. Then when the use wants to export I get the contents again and then do a search and replace for the @@ placeholders and link them properly. Then save the document to the output stream again which will then bring up the save dialog on their browser.

I am using ASP.Net MVC and am in a hosted environment. I was also maybe contemplating dynamically creating a new View type and dynamically creating new views when the user uploads a template. Not sure that this approach will work though.

Is this a good approach? What tools should I be looking at? Any other suggestions?

Was it helpful?

Solution

This is similar to an approach we took for inserting data into word documents and then returning them to the user. We opened the .docx file (it's a zip file so easy to extract) extracted the document (in the word folder called document.xml), did the replace and then put the document back into the .docx file and returned it to the user.

An issue we hit were that word inserted tags at strange places, especially things like spell/grammar errors, so we needed to be careful when we did the search/replace.

We decided not to store the fields from the document in a database to allow the documents to be easily updated.

We used dotnetzip component for opening the .docx files

Something we also did was to combine several documents into a single large document to save on the number of downloads. If I remember we used the open xml toolkit to do this merging. The website has also got loads of other information that may be of use.

OTHER TIPS

Check out Scott Guthries blog post about the new view engine code named "Razor" coming out real shortly from Microsoft. In the comments there is talk about it being able to be used in mail merge scenarios like you talk about with ASP.NET MVC views.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top