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 ();
}