≡ Menu

How to write word document in asp.net

You can add follwing code at page level function and called in button or page load

function Void GenerateWordDoc()

{

string strDocBody;

try

{

strDocBody = “<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>Dynamic Generated Document</title>”;

strDocBody = strDocBody + “<!–[if gte mso 9]>” + “<xml>” + “<w:WordDocument>” + “<w:View>Print</w:View>” + “<w:Zoom>100</w:Zoom>” + “<w:DoNotOptimizeForBrowser/>” + “</w:WordDocument>” + “</xml>” + “<![endif]–>”;

strDocBody = strDocBody + “<style> @page” + “{size:8.5in 11.0in; mso-first-footer:ff1; mso-footer: f1; mso-header: h1; border:solid navy 2.25pt; padding:24.0pt 24.0pt 24.0pt 24.0pt;” + ” margin:0.75in 0.50in 0.75in 0.50in ; “ + ” mso-header-margin:.5in; “ + ” mso-footer-margin:.5in; mso-paper-source:0;}” + ” div.Section1″ + ” {page:Section1;}” + “p.MsoFooter, li.MsoFooter, div.MsoFooter{margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:’Arial’;}” + “p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:’Arial’;}” + “–>” + “</style>” + “</head>”;

strDocBody = strDocBody + “<body lang=EN-US style=’tab-interval:.5in’>”;

//Users Content in which he want to show in word doc , in my case i call a function GetData which return string from database

strDocBody += GetData();

strDocBody += “</div> </body> </html> “;

//Force this content to be downloaded as a Word document

Response.AddHeader(“Content-Type”, “application/msword”);

Response.AddHeader(“Content-disposition”, “attachment; filename=mydoc.doc”);

Response.Charset = “”; Response.Write(strDocBody);

}

catch (Exception ex)

{

Response.Write(ex.Message);

}

}

 

{ 0 comments… add one }

Leave a Comment

Next post:

Previous post: