There's a lot of code for exporting Excel, which is the simplest:
protected void Btndcall_click (object sender, EventArgs e)
{
String datastring = DateTime.Now.ToString ("Yyyymmddhhmmss");//is the current month and minute of the day and seconds as the file name
Response.Clear ();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.appendheader ("Content-disposition", "attachment;filename=" + datastring + ". xls");
response.contentencoding = System.Text.Encoding.UTF7;
Response.ContentType = "Application/ms-excel";//Set Output file type to excel file.
System.IO.StringWriter ostringwriter = new System.IO.StringWriter ();
System.Web.UI.HtmlTextWriter ohtmltextwriter = new System.Web.UI.HtmlTextWriter (ostringwriter);
This. Gridviewall.rendercontrol (ohtmltextwriter);//gridviewall is the name of the GridView and can be placed in a table or in a DataTable
Response.Output.Write (Ostringwriter.tostring ());
Response.Flush ();
Response.End ();
}
public override void Verifyrenderinginserverform (Control control)
{
}
After exporting, if the data is more, you will encounter scientific counting problem
The workaround is to:
protected void Gridviewall_rowdatabound (object sender, GridViewRowEventArgs e)
{
if (E.row.rowtype = = Datacontrolrowtype.datarow)
{
E.row.cells[0]. Attributes.Add ("Style", "vnd.ms-excel.numberformat:@");//The column you need to process
Or all of the columns
for (int i = 0; i < E.row.cells.count; i++)
{
E.row.cells[i]. Attributes.Add ("Style", "vnd.ms-excel.numberformat:@");
}
}
}
Export to Excel and cancel the default scientific calculation method