Protected void toexcel (gridview GV, string name ){
Response. Clear ();
Response. Buffer = true;
Response. charset = "gb2312 ";
Response. appendheader ("content-disposition", "attachment; filename =" + name + ". xls ");
// If it is set to getencoding ("gb2312"), the exported file will contain garbled characters !!!
Response. contentencoding = system. Text. encoding. utf7;
Response. contenttype = "application/MS-excel"; // set the output file type to an Excel file.
System. Io. stringwriter ostringwriter = new system. Io. stringwriter ();
System. Web. UI. htmltextwriter ohtmltextwriter = new system. Web. UI. htmltextwriter (ostringwriter );
GV. rendercontrol (ohtmltextwriter );
Response. Output. Write (ostringwriter. tostring ());
Response. Flush ();
Response. End ();
}
Public override void verifyrenderinginserverform (Control)
{
}
Protected void gridview1_rowdatabound (Object sender, gridviewroweventargs E)
{
If (E. Row. rowtype = datacontrolrowtype. datarow)
{
E. Row. cells [1]. Attributes. Add ("style", "Vnd. ms-excel.numberformat :@;");
}
}
Protected void btntoexcel_click (Object sender, eventargs E)
{
If (gvstat. Rows. Count> 0 & gvstat. Visible = true ){
Toexcel (gvstat, "from" + viewstate ["startdate"]. tostring () + "to" + viewstate ["enddate"]. tostring ());
}
Else if (gvuser. Rows. Count> 0 & gvuser. Visible = true ){
Toexcel (gvuser, "from" + viewstate ["startdate"]. tostring () + "to" + viewstate ["enddate"]. tostring ());
}
}