Outputs the datagrid control content to the excel file

  • 2020-05-05 11:07:59
  • OfStack

An demo.
that outputs the contents of the datagrid control to the excel file Generate EXCEL file


public void setToExcel() 
{ 
// Response.Clear(); 
// Response.Buffer= true; 
// Response.Charset="utf-8";   
if (eformsn.Text=="") 
{ 
DataGrid1.Visible=false; 
Label1.Text=" Want to import EXCEL , please enter the application number first !"; 
Label1.Visible=true; 
} 
else 
{ 
dl.DataSource=DB("query", "select * from msi_eol_list_line where eformsn="+eformsn.Text+" order by eformsn").Tables[0].DefaultView; 
dl.DataBind(); 
// The next line is important, attachment  The parameter representation is downloaded as an attachment, which you can change to 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=EOL_"+eformsn.Text+".xls"); 
Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");  
//Response.ContentType Specify the file type   Can I do for application/ms-excel,application/ms-word ,application/ms-txt,application/ms-html Or other browsers can support documents directly  
Response.ContentType = "application/ms-excel"; 
dl.EnableViewState = false;  
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); 
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); 
// Binds the target data to the input stream output  
//this  Represents the output of this page, you can also bind datagrid, Or other support obj.RenderControl() Control of property  
dl.RenderControl(oHtmlTextWriter); 
//this.DataBind.RenderControl(oHtmlTextWriter); 
Response.Write(oStringWriter.ToString()); 
Response.End(); 
} 
} 


Related articles: