Creating Word Document Using .NET

30. October 2008

I recently had to create a Word document dynamically using .NET.

Dim filename As String = "testfile.doc"
Dim file As FileStream = New FileStream(Server.MapPath(Request.ApplicationPath & ("/documents/" & filename)), FileMode.OpenOrCreate, FileAccess.Write)
Dim Writer As StreamWriter = New StreamWriter(file)
Dim strBody As New 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>Document Title</title>")
strBody.Append("<!--[if gte mso 9]><xml>" & _
"<w:WordDocument> <w:View>" & _
"Print</w:View> <BR>" & _
"<w:Zoom>90</w:Zoom> " & _
"<w:DoNotOptimizeForBrowser/>" & _
"</w:WordDocument></xml><![endif]-->")
strBody.Append("<style><!-- /* Style Definitions" & _
" */@page Section1{size:8.27in 11.69in;" & _
"margin:.5in 1.0in .5in 1.0in;" & _
"mso-page-orientation:portrait;" & _
"mso-header-margin:.5in; " & _
"mso-footer-margin:.5in; mso-paper-source:0;" & _
"font-family: Arial; font-size: 10pt; }")
strBody.Append("div.Section1{page:Section1;}--></style></head>")
strBody.Append("div.Section1 {page:Section1;}")
strBody.Append("<style><!-- /* Style Definitions" & _
" */@page Section1{size:8.27in 11.69in;" & _
"margin:.5in 1.0in .5in 1.0in;" & _
"mso-page-orientation:portrait;" & _
"mso-header-margin:.5in; " & _
"mso-footer-margin:5in; mso-paper-source:0;" & _
"font-family: Arial; font-size: 10pt; }")
strBody.Append("div.Section1{page:Section1;}--></style></head>")
strBody.Append("div.Section1 {page:Section1;}")
strBody.Append("<body lang=EN-UK style='tab-interval:.5in'><div class=Section1>")
strBody.Append("YOUR CONTENT GOES HERE")
strBody.Append("</div></body></html>")
Writer.Write(strBody.ToString)
Writer.Close()
file.Close()

The above will create the word document to open in Page Layout and as an A4 Portrait. If you need it to be in landscape then change the style definitions to

strBody.Append("<style><!-- /* Style Definitions" & _
" */@page Section1{size:11.0in 8.5in;" & _
"margin:0.45in 0.35in 0.35in 0.35in;" & _
"mso-page-orientation: landscape;" & _
"mso-header-margin:.5in;" & _
"mso-footer-margin:.5in; mso-paper-source:0;" & _
"font-family: Arial; font-size: 10pt; }")

Thanks to Alistair Gillespie for his help with the final code.

.Net

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading





Marketing & SEO Blogs - Blog Top SitesBlog Flux Directory Marketing / SEO Top Blogs Internet Marketing & SEO (Link Building) - TOP.ORG Add to Technorati Favorites TopOfBlogs