Three steps output the ES0en.Net page to EXCEL

  • 2020-12-09 00:49:22
  • OfStack

In fact, it is easy to output WORD, EXCEL, TXT, HTM, and other types of documents with the specified content using ASP.NET. It is mainly divided into 3 steps.
1. Define document type and character encoding

 
Response.Clear(); 
   Response.Buffer= true; 
   Response.Charset="utf-8";   
   // The next line is very important,  attachment  The parameter representation is downloaded as an attachment, which you can change  online Online open  
   //filename=FileFlow.xls  Specify the name of the output file. Note that the extension matches the specified file type. It can be: .doc    .xls    .txt   .htm   
   Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls"); 
   Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");   
   //Response.ContentType Specify file type   Can I do for application/ms-excel    application/ms-word    application/ms-txt    application/ms-html     Or other browsers can directly support documents  
   Response.ContentType = "application/ms-excel"; 
   this.EnableViewState = false;   

2. Define an input stream
 
   System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); 
   System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); 

3. Bind target data to input stream output
 
this.RenderControl(oHtmlTextWriter);    
   //this  Represents the output page, which you can also bind to datagrid, Or other support obj.RenderControl() Control for properties  
   Response.Write(oStringWriter.ToString()); 
   Response.End();   

Summary: This routine has been tested on the Microsoft Visual ES19en. NET 2003 platform and is suitable for C# and VB. When using VB, the this keyword is changed to me.


Related articles: