One of my clients recently asked me to generate dynamic reports from content in the database, where the content contained Html entered by him through a WYSIWYG editor from a web application. I already had a library, that allowed considerable flexibility in generating dynamic Office documents. However, the functionality in the library was nowhere close to what the client wanted now. Html for the most part is incompatible with any native Office file format, and a conversion path could have been as complex as it could get.

Fortunately, some googling revealed that VSTO (Visual Studio Tools for Office) can accompolish this task. Seeing no other way, I had no option but to use VSTO. However, you should notice straight away that VSTO requires Office 2003 or 2007 to be installed on the machine where VSTO code is executed. Also, as it uses interop extensively, it is considerably slow.

Anyways, I could accompolish this task with the following code:

Imports Microsoft.Office.Interop.Word

Dim app As New Application
Dim d As Document = app.Documents.Open("C:\doc1.docx")

'Save html to a temp path.
Dim path As String = "C:\Windows\Temp\t1.html"
File.WriteAllText(path, html)

app.Selection.Find.ClearFormatting()
app.Selection.Find.Text = token
app.Selection.Find.Execute()
app.Selection.InsertFile(path)

d.Save()
d.Close()

app.Quit()

You should keep a couple of things in mind:

  • the Html should be well formatted with the proper html, head & body tags. The content inside the body tag would be substituted. The main html tag should have a proper DTD associated.
  • I needed to substitute the Html in place of a token. You basically need to have a valid selection. The file would be inserted in place of the selected text.
    You can use other functions for inserting Xml or other files with the same approach.

I have updated my above mentioned library now to support such insertion of Html in MS Word documents. It should not be too difficult to adapt this code for Excel documents.

UPDATE:

  1. April 27, 2012 – A Blog reader Martin Nitschke pointed out that Word stays open after executing the sample code.
    I have added the call to app.Quit() in the above example code for closing Word automatically.

    Thanks Martin for pointing that out…