Export Asp.net gridview to excel

Source: Internet
Author: User

Method 1,

(1.) default. aspx

<% @ Page Language = "C #" autoeventwireup = "true" codefile = "default. aspx. cs" inherits = "_ default" %>

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> untitled page </title>
</Head>
<Body runat = "server">
<Form ID = "form1" runat = "server">
<Div runat = "server">

<Asp: gridview id = "gridview1" runat = "server" autogeneratecolumns = "false"
Datakeynames = "customerid" datasourceid = "sqldatasource1" allowpaging = "true"
Backcolor = "lightgoldenrodyellow" bordercolor = "Tan" borderwidth = "1px"
Cellpadding = "2" forecolor = "black" gridlines = "NONE">
<Footerstyle backcolor = "Tan"/>
<Columns>
<Asp: boundfield datafield = "customerid" headertext = "customerid" readonly = "true"
Sortexpression = "customerid"/>
<Asp: boundfield datafield = "companyName" headertext = "companyName"
Sortexpression = "companyName"/>
<Asp: boundfield datafield = "contactname" headertext = "contactname"
Sortexpression = "contactname"/>
<Asp: boundfield datafield = "contacttitle" headertext = "contacttitle"
Sortexpression = "contacttitle"/>
<Asp: boundfield datafield = "Address" headertext = "Address"
Sortexpression = "Address"/>
<Asp: boundfield datafield = "city" headertext = "city" sortexpression = "city"/>
<Asp: boundfield datafield = "region" headertext = "region"
Sortexpression = "region"/>
<Asp: boundfield datafield = "postalcode" headertext = "postalcode"
Sortexpression = "postalcode"/>
<Asp: boundfield datafield = "country" headertext = "country"
Sortexpression = "country"/>
<Asp: boundfield datafield = "phone" headertext = "phone" sortexpression = "phone"/>
<Asp: boundfield datafield = "fax" headertext = "fax" sortexpression = "fax"/>
</Columns>
<Pagerstyle backcolor = "palegoldenrod" forecolor = "darkslateblue"
Horizontalalign = "center"/>
<Selectedrowstyle backcolor = "darkslateblue" forecolor = "ghostwhite"/>
<Headerstyle backcolor = "Tan" font-bold = "true"/>
<Alternatingrowstyle backcolor = "palegoldenrod"/>
</ASP: gridview>
<Asp: button id = "button1" runat = "server" onclick = "button#click" text = "Export"/>
<Br/>

</Div>
<Asp: sqldatasource id = "sqldatasource1" runat = "server"
Connectionstring = "<% $ connectionstrings: connectionstring %>"
Selectcommand = "select * From northwind. DBO. MERs"> </ASP: sqldatasource>
</Form>
</Body>
</Html>

The database settings in Web. config are as follows:

<Connectionstrings>
<Add name = "connectionstring" connectionstring = "Data Source = ccxp; user id = sa; Password = 19850613" providername = "system. Data. sqlclient"/>
</Connectionstrings>

You can set it based on your own situation.

(2.) default. aspx. CS

Using system;
Using system. configuration;
Using system. Data;
Using system. LINQ;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. htmlcontrols;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. xml. LINQ;

Public partial class _ default: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{
If (! Ispostback)
{
Databind (); // bind data
}
}
Protected void button#click (Object sender, eventargs E)
{
Response. Clear ();
System. Web. httpcontext curcontext = system. Web. httpcontext. Current;

Response. addheader ("content-disposition", "attachment?filename=filename.xls ");
Response. charset = "UTF-8"; // sets the character set
Curcontext. response. contentencoding = system. Text. encoding. utf8; // set the sequence set

Response. contenttype = "application/vnd.xls ";
System. Io. stringwriter stringwrite = new system. Io. stringwriter ();
System. Web. UI. htmltextwriter htmlwrite = new htmltextwriter (stringwrite );
Gridview1.allowpaging = false; // No paging is required for data written to excel.
Binddata ();
Gridview1.rendercontrol (htmlwrite );
Response. Write (stringwrite. tostring (); // write data to the client
Response. End ();
Gridview1.allowpaging = true; // restore the page
Binddata ();

}
Private void binddata ()
{
Gridview1.databind ();
}
Public override void verifyrenderinginserverform (Control) // if this method is left empty, the control gridview1 of the "gridview" type may be reported to be placed in the form tag with runat = server.
{
// Confirms that an htmlform control is rendered
}

}
Method 2: You do not need to override the verifyrenderinginserverform method. The button#click method is different, and the others are the same.

Protected void button#click (Object sender, eventargs E)
{

Stringbuilder sb = new stringbuilder ();
Stringwriter Sw = new stringwriter (SB );
Htmltextwriter HTW = new htmltextwriter (SW );

Page page = new page ();
Htmlform form = new htmlform ();

Gridview1.enableviewstate = false;

Page. enableeventvalidation = false;

// Realiza las inicializaciones de la instancia de la clase page que requieran los Dise n adores rad.
Page. designerinitialize ();

Page. Controls. Add (form );

Gridview1.allowpaging = false; // No paging is required for data written to excel.
Binddata ();
Form. Controls. Add (gridview1 );

Page. rendercontrol (HTW );

Response. Clear ();
Response. Buffer = true;
Response. contenttype = "application/vnd. MS-excel ";
Response. addheader ("content-disposition", "attachment?filename=data.xls ");
Response. charset = "UTF-8 ";
Response. contentencoding = encoding. default;
Response. Write (sb. tostring ());
Response. End ();

Gridview1.allowpaging = true; // restore the page
Binddata ();

}
We hope to help our friends who have such needs.

 

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.