Friday, September 21, 2012

Generating MS Word file on the fly in Asp.Net

There is a simple way in order to generate MS Word using ContentType = "application/word" but it will give you in Web Layout instead of Print Layout generally.

public void ExportToMSWord(string fileNameWord)
    {
        StringBuilder sb = new StringBuilder();
        string strBody = string.Empty;
        strBody = @"<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'>";

        strBody = strBody + "<!--[if gte mso 9]>" +
        "<xml>" +
        "<w:WordDocument>" +
        "<w:View>Print</w:View>" +
        "<w:Zoom>100</w:Zoom>" +
        "</w:WordDocument>" +
        "</xml>" +
        "<![endif]-->";

        sb.Append(strBody);
        sb.Append("<table width=\"100%\" style=\"background-color:#cfcfcf;\"><tr><td>aaaaaaaaaaa</td><td>bbbbbbbbb</td></tr></table>");

        string attachment = "attachment; filename= " + fileNameWord;
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/word";
        //StringWriter sw = new StringWriter();
        //HtmlTextWriter htw = new HtmlTextWriter(sw);
        ////this.RenderControl(htw);
        //Response.Write(strBody + sw.ToString());
        Response.Write(sb);
        Response.End();
    }


Alternatively, Interop assemblies of Microsoft Word Object Library can be used and in that case, Microsoft office version need to be aware.

No comments:

Post a Comment