/// <Summary>
/// Export the datatable content to excel and return to the Client
/// </Summary>
/// <Param name = "dgdata"> datatable to be exported </param>
Public void datatabletoexcel (system. Data. datatable dtdata)
{
System. Web. UI. webcontrols. DataGrid dgexport = NULL;
// Current Dialog
System. Web. httpcontext curcontext = system. Web. httpcontext. Current;
// Io is used to export and return an Excel file
System. Io. stringwriter strwriter = NULL;
System. Web. UI. htmltextwriter htmlwriter = NULL;
If (dtdata! = NULL)
{
// Set the encoding and attachment format
// Response. contenttype specifies the file type, which can be application/MS-Excel, application/MS-word, application/MS-txt, and application/MS-HTML.
Curcontext. response. contenttype = "application/vnd. MS-excel ";
Curcontext. response. contentencoding = system. Text. encoding. utf8;
Response. charset = "gb2312 ";
// The following line is very important. The attachment parameter indicates downloading as an attachment. You can change it to online.
// Filename=fileflow.xls specifies the name of the output file. Note that the extension is consistent with the specified file type. It can be. Doc. xls. txt. htm.
Response. appendheader ("content-disposition", "attachment; filename =" + server. urlencode ("employee information table .xls "));
// Curcontext. response. charset = "";
// Export an Excel file
Strwriter = new system. Io. stringwriter ();
Htmlwriter = new system. Web. UI. htmltextwriter (strwriter );
// To solve the possible paging problem in dgdata, You need to redefine a non-Paging DataGrid.
Dgexport = new system. Web. UI. webcontrols. DataGrid ();
Dgexport. datasource = dtdata. defaultview;
Dgexport. allowpaging = false;
// The Key to handling ID card numbers is this event
Dgexport. itemdatabound + = new system. Web. UI. webcontrols. datagriditemeventhandler (gridhrinfo_itemdatabound1 );
Dgexport. databind ();
// Return to the Client
Dgexport. rendercontrol (htmlwriter );
Curcontext. response. Write (strwriter. tostring ());
// Curcontext. Flush ();
Curcontext. response. End ();
}
}
// This event is used to handle the 18-digit ID card number. When the DataGrid is bound
Protected void gridhrinfo_itemdatabound1 (Object sender, datagriditemeventargs E)
{
If (E. Item. itemtype = listitemtype. Item | E. Item. itemtype = listitemtype. alternatingitem)
{
// Cells [10] indicates the data column to be processed in the table (column 10th is the ID card column)
E. Item. cells [10]. Attributes. Add ("style", "Vnd. ms-excel.numberformat :@");
}
}
Appendix:
Common formats are listed below:
1) Text: VND. ms-excel.numberformat :@
2) Date: VND. ms-excel.numberformat: yyyy/mm/dd
3) number: VND. ms-excel.numberformat: #,## 0.00
4) Currency: VND. ms-excel.numberformat: ¥ #, #0.00
5) percentage: VND. ms-excel.numberformat: # 0.00%