Export data tables in a database to Excel with C # ASP.

Source: Internet
Author: User

You need to use the component GridView and a button.

Add a data source to the GridView

Select the field of the table in the database you want, and the data will be displayed in the GridView after the add succeeds.

Add a button, double-click the control to add the corresponding function code

The function code is as follows:

protected void Button1_Click (object sender, EventArgs e)        {        string FileName = "Score Table" + DateTime.Now + ". xls";        Response.Charset = "GB2312";        response.contentencoding = System.text.encoding.utf8;//system.text        //If the settings GB2312 appear garbled        Response.AddHeader ( "Content-disposition", "attachment;filename=" + httputility.urlencode (filename, System.Text.Encoding.UTF8). ToString ());        Response.AddHeader ("Content-type", "application/ms-excel");//Set the output file type        //or Response.ContentType = FileType;        Define an output stream        stringwriter tw = new StringWriter ();//system.io        HtmlTextWriter hw = new HtmlTextWriter (TW);        Gridview1.rendercontrol (HW);//gridview bound        Response.Write (tw. ToString ());        Response.End ();    }    public override void Verifyrenderinginserverform (Control control)    {//must write this;    }        }

Specific function code to add some of the namespace references, can be found in Baidu.

Last Test results Double click Export, prompt to download

Export data tables in a database to Excel with C # ASP.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.