Copy Code code as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Data. SqlClient;
Using System.Data;
public partial class _default:system.web.ui.page
{
protected void Page_Load (object sender, EventArgs e)
{
String sqlconn = "server=.; database=db; Integrated SECURITY=SSPI ";
String sql = "SELECT top * from table";
SqlConnection myconnection = new SqlConnection (sqlconn);//Create a database connection instance
Myconnection.open (); Open Database
SqlCommand mycommand = new SqlCommand (sql, MyConnection);//Create an instance of SQL, execute a SQL
SqlDataAdapter Adapter = new SqlDataAdapter ();//create a SQL data adapter
Adapter.selectcommand = mycommand;//Property set to retrieve records from the data source
DataSet myds = new DataSet (); Create a DataSet instance
Adapter.fill (myds)//Fill DataSet
Gridview1.datasource = Myds.tables[0]. defaultview;//
Gridview1.databind ();
Datatoexcel ("Test Cxcel", GridView1);
Myconnection.close ()//Close database connection
}
public void Datatoexcel (string fileName, GridView MyGridView)
{
Define document type, character encoding
Response.Clear ();
Response.Buffer = false;
Response.Charset = "Utf-8";
Response.Charset = "GB2312";
The following line is very important, the attachment parameter means that as an attachment to download, you can change to online open
Filename=fileflow.xls Specify the name of the output file, note that its extension matches the specified file type, and can be:. doc | | . xls | | . txt | |. Htm
Response.appendheader ("Content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode (filename, SYSTEM.TEXT.ENCODING.UTF8) + ". xls");
response.contentencoding = System.Text.Encoding.GetEncoding ("Utf-8");
response.contentencoding = System.Text.Encoding.GetEncoding ("GB2312");
RESPONSE.CONTENTTYPE Specifies that the file type can be Application/ms-excel | | Application/ms-word | | Application/ms-txt | | application/ms-html | | or other browsers to support documents directly
Response.ContentType = "Application/ms-excel";
This. EnableViewState = false;
System.Globalization.CultureInfo Mycitrad = new System.Globalization.CultureInfo ("ZH-CN", true);
Define an input stream
System.IO.StringWriter ostringwriter = new System.IO.StringWriter ();
System.Web.UI.HtmlTextWriter ohtmltextwriter = new System.Web.UI.HtmlTextWriter (ostringwriter);
Bind the target data to the input stream output
Mygridview.rendercontrol (Ohtmltextwriter);
Response.Write (Ostringwriter.tostring ());
Response.End ();
}
The following empty statement must be added, or it will appear "must be placed in a form tag with Runat=server." "The error
public override void Verifyrenderinginserverform (Control control)
{
}
Click events to generate Excel
protected void Button1_Click (object sender, EventArgs e)
{
Datatoexcel ("Test Cxcel", GridView1);
}
}