5,696,038 members and growing! (13,402 online)
Email Password   helpLost your password?
Enterprise Systems » Office Development » Microsoft Word     Intermediate

Dynamically generate a MS Word document using HTML & CSS

By 'Anil' Radhakrishna

A lightweight method to generate a Word document without using any components and show it in Print Layout.
VB.NET 1.1, NT4, Win2K, WinXP, Win2003, Windows, .NET, Visual Studio, Dev

Posted: 7 Jun 2004
Updated: 23 Jun 2006
Views: 161,894
Bookmarked: 97 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
55 votes for this Article.
Popularity: 7.00 Rating: 4.02 out of 5
8 votes, 14.8%
1
1 vote, 1.9%
2
0 votes, 0.0%
3
13 votes, 24.1%
4
32 votes, 59.3%
5

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

About the Author

'Anil' Radhakrishna


'Anil' Radhakrishna is a seasoned developer and a Microsoft MVP (ASP/ASP.NET). He blogs his little discoveries and Web development tips, tricks and trivia quite regularly. You can find some of his unusual code samples & snippets at his Code Gallery.

Occupation: Web Developer
Location: India India

Other popular Office Development articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 59 (Total in Forum: 59) (Refresh)FirstPrevNext
GeneralHeader Footer appears twicemembermikeb5510:04 22 Aug '08  
GeneralHow can be the images also be incorporated in the word document ?membergaurav200721:18 5 Jun '08  
GeneralRe: How can be the images also be incorporated in the word document ?memberTerry Meritt11:16 15 Oct '08  
GeneralRe: How can be the images also be incorporated in the word document ?memberMember 45704120:08 30 Oct '08  
GeneralSom problem with different charactersmemberb3rra4:47 7 May '08  
GeneralRe: Som problem with different charactersmember'Anil' Radhakrishna5:18 7 May '08  
GeneralRe: Som problem with different charactersmemberb3rra5:39 7 May '08  
GeneralYou Rock.memberMember 43049588:17 26 Jan '08  
QuestionSaving the filememberMember 322823919:17 13 Dec '07  
QuestionHow to save the generated documentmemberMember 322823919:16 13 Dec '07  
GeneralHeader and footer after dynamic generation of word docmemberraliravibabu20:19 15 Aug '07  
QuestionRe: Header and footer after dynamic generation of word docmemberdrkivel17:59 17 Oct '07  
GeneralWhat about security rights?memberDmitry Dzygin4:34 26 Jun '07  
GeneralPutting Imagemembersatejprabhu21:33 8 Jun '07  
QuestionHow to get the lis of heading without Table of contentsmemberLokanatha Reddy23:45 1 Apr '07  
AnswerRe: How to get the lis of heading without Table of contentsmember'Anil' Radhakrishna0:36 11 Apr '07  
QuestionWhat am I missing..........LeighmemberLeighG10:02 20 Feb '07  
AnswerRe: What am I missing..........Leighmember'Anil' Radhakrishna19:16 20 Feb '07  
QuestionAdding header and footermember1:16 23 Jan '07  
AnswerRe: Adding header and footermember'Anil' Radhakrishna19:48 15 Feb '07  
GeneralHeader, footer and foot notemember22:23 22 Jan '07  
QuestionNewbe needs helpmembersstark08:54 26 Sep '06  
Generalpage breaks?memberwalkerla8:22 14 Sep '06  
GeneralRe: page breaks?memberwalkerla13:51 14 Sep '06  
GeneralRe: page breaks?memberRolfpants7:04 19 Sep '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 Jun 2006
Editor: Smitha Vijayan
Copyright 2004 by 'Anil' Radhakrishna
Everything else Copyright © CodeProject, 1999-2008
Web08 | Advertise on the Code Project