Export the data in the gridview to excel to download and solve the Garbled text problem.
During the software development process, we often export the data in the gridview to excel for the client to download. The following provides a solution for your reference. You are welcome to discuss and raise some shortcomings, to achieve mutual learning and mutual improvement.
Step 1:
Add the following event to the page where the gridview is located
// Download the gridview and add the following events;
Public Override Void Verifyrenderinginserverform (Control)
{
}
Step 2:
The call method is as follows:
/**/ /// </Summary>
/// <Param name = "G"> The gridview to download </Param>
/// <Param name = "FILENAME"> File Name; </Param>
/// <Param name = "table"> Data source, in order to solve the paging Problem </Param>
Public Static Void Download (gridview G, String Filename, datatable table)
{
G. datasource = Table;
G. allowpaging = False ;
G. databind ();
Filename = Httputility. urlencode (filename + " . Xls " , Encoding. getencoding ( " UTF-8 " ));
Httpcontext. Current. response. Clear ();
Httpcontext. Current. response. addheader ( " Content-Disposition " , " Attachment; filename = " + Filename );
Httpcontext. Current. response. Write ( " <Meta http-equiv = Content-Type content = text/html; charset = UTF-8> " );
// Response. addheader ("content-disposition", "attachment?filename=filename.doc "); // Can be imported into word;
Httpcontext. Current. response. charset = " UTF-8 " ;
Httpcontext. Current. response. contenttype = " Application/vnd.xls " ;
System. Io. stringwriter stringwrite = New System. Io. stringwriter ();
Showgridviewheader. onlyshowgridviewheader (g );
System. Web. UI. htmltextwriter htmlwrite = New Htmltextwriter (stringwrite );
G. rendercontrol (htmlwrite );
Httpcontext. Current. response. Write (stringwrite. tostring ());
Httpcontext. Current. response. End ();
}
The above two steps can be used to export and download the data in the gridview. If no garbled characters have occurred after the download, congratulations. some computers may be garbled during data download, but some computers may not. the solution is as follows:
Solution
1. The saved file name cannot contain Chinese characters. If you want to use Chinese characters, encode them;
2. Configure web. configCodeAs follows:
< System. Web >
< Globalization requestencoding = " UTF-8 " Responseencoding = " UTF-8 " />
</ System. Web >