Wednesday, November 10, 2010
Export to word From Asp.Net
The below C# .Net code will export the data in the data table Dt_Export to an MS word format document. This will be needed in many of the Asp.net application.
Before using this code. Make a template in word, Then save it as Word XML document (File Version 2003 ). Now open it with Notepad or an HTML / XML editor Insert a {0} symbol at the place where you would like the data to be appeared, Now when you do the String.Format {0} will be replace with the required data in the tabular format. This uses XML word format
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | System.Text.StringBuilder Row_Template = new System.Text.StringBuilder(); Row_Template.Append( "<w:tr ><w:tc><w:tcPr><w:tcW w:w='2323' w:type='dxa'/></w:tcPr><w:p><w:pPr><w:jc w:val='center'/>" ); Row_Template.Append( "</w:pPr><w:r><w:t>{0}</w:t></w:r></w:p></w:tc>" ); Row_Template.Append( "<w:tc><w:tcPr><w:tcW w:w='5387' w:type='dxa'/></w:tcPr><w:p><w:pPr><w:jc w:val='center'/></w:pPr><w:r><w:t>{1}</w:t></w:r></w:p></w:tc>" ); Row_Template.Append( "<w:tc><w:tcPr><w:tcW w:w='2346' w:type='dxa'/></w:tcPr><w:p><w:pPr><w:jc w:val='center'/></w:pPr><w:r><w:t>{2}</w:t></w:r></w:p></w:tc></w:tr>" ); foreach (DataRow dr in Dt_Exprt.Rows) { Acct_NO = dr[0].ToString(); Vnd_Name = dr[1].ToString().Replace( "&" , "&" ); LST_TRNSDT = Convert.ToDateTime(dr[2]).ToString( "MM/dd/yyyy" ); WordDoc_RowCollection += string .Format(Row_Template.ToString(), Acct_NO, Vnd_Name, LST_TRNSDT); } Response.Clear(); Response.ClearHeaders(); Response.Charset = "" ; string attachment = "attachment; filename=MYwordDocTemplate.Doc" ; Response.ClearContent(); Response.AppendHeader( "content-disposition" , attachment); Response.ContentType = "application/vnd.ms-word" ; Response.BufferOutput = false ; //System.IO.StringWriter tw = new System.IO.StringWriter(); //System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); //DG.RenderControl(hw); Word_Doc = string .Format(Word_Doc, WordDoc_RowCollection); Response.Write(Word_Doc); Response.End(); |