Click here to Skip to main content
15,867,986 members
Articles / Programming Languages / Visual Basic
Article

Dynamically generate a MS Word document using HTML & CSS

Rate me:
Please Sign up or sign in to vote.
4.63/5 (71 votes)
23 Jun 20062 min read 755.5K   148   99
A lightweight method to generate a Word document without using any components and show it in Print Layout.

Introduction

This article explains how easy it is to generate reports dynamically in a visually rich and appealing format like MS-Word (2000 and above) without using any components, and shows a little workaround for a quirk. It also talks about the connection between Office, XML, and HTML.

Documents can be converted from Word to HTML (File->Save As) and vice versa! To create a dynamic Word report, you will need to generate regular HTML text and apply the required formatting through CSS. You can even incorporate stuff from the database into the Word report. By playing around with MIME settings, you can force the HTML content to be downloaded as a Word .doc file.

Here comes the code

When you save the downloaded Word document and open it, it opens in the Web Layout format. Now, wouldn't it be neater if it opened in the default Print Layout? Well, all you need to do is attach the style properties. Here comes the code:

VB
Public Sub Page_Load(sender as Object, e as EventArgs)

    'build the content for the dynamic Word document
    'in HTML alongwith some Office specific style properties. 
    Dim strBody As New System.Text.StringBuilder("")

    strBody.Append("<html " & _ 
            "xmlns:o='urn:schemas-microsoft-com:office:office' " & _
            "xmlns:w='urn:schemas-microsoft-com:office:word'" & _ 
            "xmlns='http://www.w3.org/TR/REC-html40'>" & _
            "<head><title>Time</title>") 

    'The setting specifies document's view after it is downloaded as Print
    'instead of the default Web Layout
    strBody.Append("<!--[if gte mso 9]>" & _
                             "<xml>" & _ 
                             "<w:WordDocument>" & _
                             "<w:View>Print</w:View>" & _
                             "<w:Zoom>90</w:Zoom>" & _ 
                             "<w:DoNotOptimizeForBrowser/>" & _
                             "</w:WordDocument>" & _
                             "</xml>" & _ 
                             "<![endif]-->")

    strBody.Append("<style>" & _
                            "<!-- /* Style Definitions */" & _
                            "@page Section1" & _
                            "   {size:8.5in 11.0in; " & _
                            "   margin:1.0in 1.25in 1.0in 1.25in ; " & _
                            "   mso-header-margin:.5in; " & _
                            "   mso-footer-margin:.5in; mso-paper-source:0;}" & _
                            " div.Section1" & _
                            "   {page:Section1;}" & _
                            "-->" & _
                           "</style></head>") 

    strBody.Append("<body lang=EN-US style='tab-interval:.5in'>" & _
                            "<div class=Section1>" & _
                            "<h1>Time and tide wait for none</h1>" & _ 
                            "<p style='color:red'><I>" & _
                            DateTime.Now & "</I></p>" & _
                            "</div></body></html>") 

    'Force this content to be downloaded 
    'as a Word document with the name of your choice
    Response.AppendHeader("Content-Type", "application/msword")
    Response.AppendHeader ("Content-disposition", _
                           "attachment; filename=myword.doc")
    Response.Write(strBody)
End Sub

Click here to try it out.

If you wish to dig deeper into other style properties that you would like to implement, create the Word document in the required fashion, save the Word document as an HTML file, and view the source for the style settings. Wonderful, right?

This article just touches the tip of the iceberg. There are other good resources too. Microsoft Office 2000 supports Hypertext Markup Language (HTML) as a native file format. To get a low-down on this technique, you can download the Microsoft Office HTML and XML Reference that describes the files saved by Excel, PowerPoint, and Word when a document, presentation, workbook, or worksheet is saved as a Web page. You can play around with the style settings to create different configurable options for the user to view a downloadable Word document.

MS Word has better support now for HTML. You can even use it as an HTML editor. The Office HTML Filter is a handy tool you can use to remove Office-specific markup tags embedded in Office 2000 documents saved as HTML to give you really lean and mean HTML code. Even the most basic Windows users are well conversant with Word. Generating HTML files could not have got easier than this, and folks new to HTML do not have to get entangled in tags.

While on the topic, developers can checkout Peter Bromberg’s article: Build a C# Multipart MIME Encoding Library to Save Web Pages in "MHT" Format, on embedding images into a Word document.

Conclusion

This article tip shows a lightweight method to generate a Word document without using any components, and show it in Print Layout. If you have any nifty Office tips related to HTML and XML, please do share.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect
India India
'Anil' Radhakrishna is a seasoned architect who enjoys working with Microsoft tools & technologies. He blogs quite regularly about his little discoveries and technical experiments on his blog called Tech Tips, Tricks & Trivia. He loves building mash-ups using public Web APIs.

Comments and Discussions

 
GeneralAnother office tips Pin
Inlyrib23-Oct-15 2:28
Inlyrib23-Oct-15 2:28 
QuestionCame up with unwanted square character symbol Pin
s.v.lakum9-Nov-14 20:36
professionals.v.lakum9-Nov-14 20:36 
AnswerRe: Came up with unwanted square character symbol Pin
'Anil' Radhakrishna10-Nov-14 15:40
'Anil' Radhakrishna10-Nov-14 15:40 
GeneralRe: Came up with unwanted square character symbol Pin
arun_sh9916-Jul-15 2:39
arun_sh9916-Jul-15 2:39 
QuestionHow to make its default save type is .doc Pin
JeevanJ26-Apr-13 1:57
JeevanJ26-Apr-13 1:57 
AnswerRe: How to make its default save type is .doc Pin
JeevanJ28-Apr-13 22:38
JeevanJ28-Apr-13 22:38 
GeneralRe: How to make its default save type is .doc Pin
Mitesh Golwala1-Apr-18 19:12
Mitesh Golwala1-Apr-18 19:12 
GeneralMy vote of 5 Pin
Tejas Vaishnav31-Oct-12 20:39
professionalTejas Vaishnav31-Oct-12 20:39 
QuestionFor Header and footer with image Pin
prateekfgiet17-Oct-12 4:50
prateekfgiet17-Oct-12 4:50 
GeneralMy vote of 5 Pin
hadi552615-Jul-12 19:15
hadi552615-Jul-12 19:15 
GeneralMy vote of 5 Pin
giorgio19514-Apr-12 3:43
giorgio19514-Apr-12 3:43 
Very useful. I found it exactly what I wanted.
Thank you, Anil!
QuestionFor DOCX Pin
Johnny Glenn13-Mar-12 2:21
Johnny Glenn13-Mar-12 2:21 
QuestionMargins Pin
HerndonDLR19-Dec-11 2:06
HerndonDLR19-Dec-11 2:06 
QuestionAdapt ASP code to PHP Pin
User 84386119-Dec-11 2:58
User 84386119-Dec-11 2:58 
AnswerRe: Adapt ASP code to PHP Pin
'Anil' Radhakrishna9-Dec-11 3:31
'Anil' Radhakrishna9-Dec-11 3:31 
GeneralMy vote of 5 Pin
walanga30-Sep-11 19:29
walanga30-Sep-11 19:29 
QuestionDatagrid Pin
Mevin SM29-Sep-11 2:10
Mevin SM29-Sep-11 2:10 
GeneralMy vote of 5 Pin
Aby Watson24-Feb-11 22:43
Aby Watson24-Feb-11 22:43 
GeneralMy vote of 2 Pin
Santhosh Kumar Gudise21-Dec-10 22:55
Santhosh Kumar Gudise21-Dec-10 22:55 
QuestionHow do I save this generated word doc? Pin
Member 747702829-Sep-10 3:07
Member 747702829-Sep-10 3:07 
AnswerRe: How do I save this generated word doc? Pin
'Anil' Radhakrishna31-Jan-11 16:00
'Anil' Radhakrishna31-Jan-11 16:00 
GeneralHeader and Footer Duplicating Pin
kimberly.johnson335-Mar-10 9:49
kimberly.johnson335-Mar-10 9:49 
GeneralRe: Header and Footer Duplicating Pin
bborton13-Jul-10 10:54
bborton13-Jul-10 10:54 
GeneralRe: Header and Footer Duplicating Pin
'Anil' Radhakrishna1-Sep-10 6:52
'Anil' Radhakrishna1-Sep-10 6:52 
GeneralRe: Header and Footer Duplicating Pin
bborton1-Sep-10 6:56
bborton1-Sep-10 6:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.