Gridview operation: Export Excel [solution 2]

Source: Internet
Author: User

Gridview exports an Excel file. solution 2: Write the table directly to the response

By chance, because no Content-Type is written, the response outputs a table,

Therefore, the gridview ultview of the gridview in solution 1 written in the response actually has only one table without any style attribute.

Therefore, inputting a table in the response can naturally achieve the same purpose.

In addition, you can easily set different columns of a sheet in Excel.

Private void outtoexcel ()
{
Httpcontext curcontext = system. Web. httpcontext. Current;
Stringwriter strwriter = new stringwriter ();
Curcontext. response. contenttype = "application/vnd. MS-excel ";

Curcontext. response. addheader ("content-disposition", "attachment; filename =" +

Httputility. urlencode ("- .xls "));


Curcontext. response. contentencoding = encoding. utf8;

Curcontext. response. charset = "utf8 ";

// Obtain the CDT in the same way as the gridview data source on the page.
Datatable CDT = datasinfo. datalayer. dboper. w_categoryproperty.getviews ();
String TXT = "<Table width = '000000' border = '1' cellpadding = '0' cellspacing = '0'>" +
"<Caption> Attribute-attribute value </caption> ";
TXT + = "<tr> ";
TXT + = "<TD> name </TD> ";
TXT + = "<TD> property id </TD> ";
TXT + = "<TD> value id </TD> ";
TXT + = "</tr> ";
Foreach (datarow DR in CDT. Rows)
{
TXT + = "<tr> ";
TXT + = "<TD>" + Dr ["cname"]. tostring () + "</TD> ";
TXT + = "<TD>" + Dr ["CID"]. tostring () + "</TD> ";
TXT + = "<TD>" + Dr ["PID"]. tostring () + "</TD> ";
TXT + = "</tr> ";
}
TXT + = "</table> ";

Curcontext. response. Write (txt );
Curcontext. response. End ();
}

 

 

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.