Private void toexcel (String title)
{
Response. Clear ();
Response. Buffer = false;
Response. charset = "UTF-8 ";
Response. appendheader ("content-disposition", "attachment; filename =" + httputility. urlencode (title) + ". xls ");
Response. contentencoding = system. Text. encoding. utf8;
Response. contenttype = "application/MS-excel ";
Response. Write ("<meta http-equiv = Content-Type content = \" text/html; charset = UTF-8 \ "> ");
This. enableviewstate = false;
System. Io. stringwriter ostringwriter = new system. Io. stringwriter ();
Htmltextwriter ohtmltextwriter = new htmltextwriter (ostringwriter );
Gridview1.rendercontrol (ohtmltextwriter); // convert the numeric character to the text format after exporting the Excel file; otherwise, the previous 0 characters are automatically discarded.
Response. Write (addexcelhead ());
Response. Write (ostringwriter. tostring ());
Response. Write (addexcelbottom ());
Response. End ();
}
Protected void btn_toexcel_click (Object sender, eventargs E)
{
Toexcel ("Order details ");
}
Public static string addexcelhead ()
{
Stringbuilder sb = new stringbuilder ();
SB. append ("<HTML xmlns: x = \" urn: Schemas-Microsoft-com: Office: Excel \ "> ");
SB. append ("SB. append ("<! -- [If gte mso 9]> <XML> ");
SB. append ("<X: excelworkbook> ");
SB. append ("<X: excelworksheets> ");
SB. append ("<X: excelworksheet> ");
SB. append ("<X: Name> </X: Name> ");
SB. append ("<X: worksheetoptions> ");
SB. append ("<X: Print> ");
SB. append ("<X: validprinterinfo/> ");
SB. append ("</X: Print> ");
SB. append ("</X: worksheetoptions> ");
SB. append ("</X: excelworksheet> ");
SB. append ("</X: excelworksheets> ");
SB. append ("</X: excelworkbook> ");
SB. append ("</XML> ");
SB. append ("<! [Endif] --> ");
SB. append ("SB. append ("<body> ");
Return sb. tostring ();
}
Public static string addexcelbottom ()
{
Stringbuilder sb = new stringbuilder ();
SB. append ("</body> ");
SB. append ("Return sb. tostring ();
}
// Solve the problem again: The gridview1 control of the type gridview must be placed in the form tag with runat = Server
Public override void verifyrenderinginserverform (Control)
{
}