Click here to Skip to main content
11,496,146 members (388 online)
Click here to Skip to main content

Dynamically generate a MS Word document using HTML & CSS

, 23 Jun 2006 440.7K 139
A lightweight method to generate a Word document without using any components and show it in Print Layout.
The site is currently in read-only mode for maintenance. Posting of new items will be available again shortly.

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:

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

Share

About the Author

'Anil' Radhakrishna
Web Developer
India India
'Anil' Radhakrishna is a seasoned developer 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. You can find some of his unusual code samples & snippets at his Code Gallery. He loves building mash-ups using public Web APIs.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
QuestionCame up with unwanted square character symbol Pin
s.v.lakum9-Nov-14 21:36
professionals.v.lakum9-Nov-14 21:36 
AnswerRe: Came up with unwanted square character symbol Pin
'Anil' Radhakrishna10-Nov-14 16:40
member'Anil' Radhakrishna10-Nov-14 16:40 
QuestionHow to make its default save type is .doc Pin
jeevanjoshi26-Apr-13 2:57
memberjeevanjoshi26-Apr-13 2:57 
AnswerRe: How to make its default save type is .doc Pin
jeevanjoshi28-Apr-13 23:38
memberjeevanjoshi28-Apr-13 23:38 
GeneralMy vote of 5 Pin
Tejas Vaishnav31-Oct-12 21:39
memberTejas Vaishnav31-Oct-12 21:39 
QuestionFor Header and footer with image Pin
prateekfgiet17-Oct-12 5:50
memberprateekfgiet17-Oct-12 5:50 
GeneralMy vote of 5 Pin
hadi552615-Jul-12 20:15
memberhadi552615-Jul-12 20:15 
GeneralMy vote of 5 Pin
giorgio19514-Apr-12 4:43
membergiorgio19514-Apr-12 4:43 
Very useful. I found it exactly what I wanted.
Thank you, Anil!
QuestionFor DOCX Pin
Johnny Glenn13-Mar-12 3:21
memberJohnny Glenn13-Mar-12 3:21 
QuestionDocentric - Another COM free solution Pin
Jure.L29-Dec-11 0:10
memberJure.L29-Dec-11 0:10 
QuestionMargins Pin
Member 850067719-Dec-11 3:06
memberMember 850067719-Dec-11 3:06 
QuestionAdapt ASP code to PHP Pin
Peter Trumbull9-Dec-11 3:58
memberPeter Trumbull9-Dec-11 3:58 
AnswerRe: Adapt ASP code to PHP Pin
'Anil' Radhakrishna9-Dec-11 4:31
member'Anil' Radhakrishna9-Dec-11 4:31 
GeneralMy vote of 5 Pin
walanga30-Sep-11 20:29
memberwalanga30-Sep-11 20:29 
QuestionDatagrid Pin
Member 275668529-Sep-11 3:10
memberMember 275668529-Sep-11 3:10 
GeneralMy vote of 5 Pin
Aby Watson24-Feb-11 23:43
memberAby Watson24-Feb-11 23:43 
GeneralMy vote of 2 Pin
santhu12smart21-Dec-10 23:55
membersanthu12smart21-Dec-10 23:55 
QuestionHow do I save this generated word doc? Pin
Member 747702829-Sep-10 4:07
memberMember 747702829-Sep-10 4:07 
AnswerRe: How do I save this generated word doc? Pin
'Anil' Radhakrishna31-Jan-11 17:00
member'Anil' Radhakrishna31-Jan-11 17:00 
GeneralHeader and Footer Duplicating Pin
kimberly.johnson335-Mar-10 10:49
memberkimberly.johnson335-Mar-10 10:49 
GeneralRe: Header and Footer Duplicating Pin
bborton13-Jul-10 11:54
memberbborton13-Jul-10 11:54 
GeneralRe: Header and Footer Duplicating Pin
'Anil' Radhakrishna1-Sep-10 7:52
member'Anil' Radhakrishna1-Sep-10 7:52 
GeneralRe: Header and Footer Duplicating Pin
bborton1-Sep-10 7:56
memberbborton1-Sep-10 7:56 
GeneralPlease help to put Header and Footer Pin
Himanshu_prem5-Jan-10 1:12
memberHimanshu_prem5-Jan-10 1:12 
QuestionHow can we close the browser window once download is completed?? Pin
Nabin Kumar Jha6-Nov-09 7:14
memberNabin Kumar Jha6-Nov-09 7:14 
GeneralUnable to run Pin
cdjohn13-Sep-09 23:26
membercdjohn13-Sep-09 23:26 
QuestionLarge document, takes a very long time to open...any advice? Pin
autumnEND6-May-09 4:56
memberautumnEND6-May-09 4:56 
AnswerRe: Large document, takes a very long time to open...any advice? Pin
kayaker41126-May-09 9:48
memberkayaker41126-May-09 9:48 
GeneralRe: Large document, takes a very long time to open...any advice? Pin
'Anil' Radhakrishna26-May-09 16:25
member'Anil' Radhakrishna26-May-09 16:25 
GeneralDuplicate header / footer Pin
Sam Horne25-Mar-09 19:12
memberSam Horne25-Mar-09 19:12 
GeneralEmbedding USERINITIALS into HTML Pin
cwhite3075530-Dec-08 4:06
membercwhite3075530-Dec-08 4:06 
GeneralRe: Embedding USERINITIALS into HTML Pin
'Anil' Radhakrishna24-Mar-09 1:08
member'Anil' Radhakrishna24-Mar-09 1:08 
GeneralHeader Footer appears twice Pin
mikeb5522-Aug-08 10:04
membermikeb5522-Aug-08 10:04 
GeneralRe: Header Footer appears twice Pin
Sam Horne25-Mar-09 19:11
memberSam Horne25-Mar-09 19:11 
GeneralRe: Header Footer appears twice Pin
DLonghofer29-Jun-10 8:45
memberDLonghofer29-Jun-10 8:45 
QuestionHow can be the images also be incorporated in the word document ? Pin
gaurav20075-Jun-08 21:18
membergaurav20075-Jun-08 21:18 
AnswerRe: How can be the images also be incorporated in the word document ? Pin
Terry Meritt15-Oct-08 11:16
memberTerry Meritt15-Oct-08 11:16 
GeneralRe: How can be the images also be incorporated in the word document ? Pin
Member 457041230-Oct-08 0:08
memberMember 457041230-Oct-08 0:08 
GeneralRe: How can be the images also be incorporated in the word document ? Pin
Terry Meritt13-Apr-09 7:30
memberTerry Meritt13-Apr-09 7:30 
GeneralRe: How can be the images also be incorporated in the word document ? Pin
lakpa13-Apr-09 1:56
memberlakpa13-Apr-09 1:56 
GeneralSom problem with different characters Pin
b3rra7-May-08 4:47
memberb3rra7-May-08 4:47 
GeneralRe: Som problem with different characters Pin
'Anil' Radhakrishna7-May-08 5:18
member'Anil' Radhakrishna7-May-08 5:18 
GeneralRe: Som problem with different characters Pin
b3rra7-May-08 5:39
memberb3rra7-May-08 5:39 
GeneralRe: Som problem with different characters Pin
Recep GUVEN2-Feb-11 10:51
memberRecep GUVEN2-Feb-11 10:51 
GeneralYou Rock. Pin
Member 430495826-Jan-08 8:17
memberMember 430495826-Jan-08 8:17 
QuestionSaving the file Pin
Member 322823913-Dec-07 19:17
memberMember 322823913-Dec-07 19:17 
QuestionHow to save the generated document Pin
Member 322823913-Dec-07 19:16
memberMember 322823913-Dec-07 19:16 
GeneralHeader and footer after dynamic generation of word doc Pin
raliravibabu15-Aug-07 20:19
memberraliravibabu15-Aug-07 20:19 
QuestionRe: Header and footer after dynamic generation of word doc Pin
drkivel17-Oct-07 17:59
memberdrkivel17-Oct-07 17:59 
QuestionWhat about security rights? Pin
Dmitry Dzygin26-Jun-07 4:34
memberDmitry Dzygin26-Jun-07 4:34 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150520.1 | Last Updated 23 Jun 2006
Article Copyright 2004 by 'Anil' Radhakrishna
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid