Private void exportexcelfromdatagrid
(String filename, system. Web. UI. webcontrols. DataGrid toexcelgrid)
...{
Response. Clear ();
Response. Buffer = true;
Response. charset = "UTF-8 ";
Response. appendheader ("content-disposition", "attachment; filename =" + server. urlencode (filename ));
Response. contentencoding = system. Text. encoding. Default; // set the output stream to simplified Chinese
Response. contenttype = "application/MS-excel"; // set the output file type to an Excel file.
This. enableviewstate = false;
System. Globalization. cultureinfo mycitrad =
New system. Globalization. cultureinfo ("ZH-CN", true );
System. Io. stringwriter ostringwriter = new system. Io. stringwriter (mycitrad );
System. Web. UI. htmltextwriter ohtmltextwriter =
New system. Web. UI. htmltextwriter (ostringwriter );
Toexcelgrid. rendercontrol (ohtmltextwriter );
Response. Write (ostringwriter. tostring ());
Response. End ();
}
Private void button4_click (Object sender, system. eventargs E)
...{
This. panel1.visible = false;
String filename = "internal trainer .xls ";
This. Maid [6]. Visible = true;
This. Maid [7]. Visible = true;
This. Maid [This. Maid. Count-1]. Visible = false ;//*
This. Maid [This. Maid. Count-2]. Visible = false ;//*
This. datagrid1.allowsorting = false ;//*
This. Maid = false;
This. Maid =-1 ;//*
This. bindgrid ();
This. exportexcelfromdatagrid (filename, this. datagrid1 );
}
}
The principle is to use the rendercontrol method of the DataGrid (actually its parent class control) to output the HTML code into the buffer zone during the appearance of the entire DataGrid, and set the contenttype, let Excel's automatic error correction function save this output as an Excel file.
Many friends on the Internet use the above Code that is highly flexible and can be found to be useless. The returned errors are similar:
"Linkbutton must be placed in a form with the runat = server label", and more users say:
The problem is obvious, because the DataGrid is not placed in the form of runat = server, you can add it.
In my opinion, this answer is not accurate for the following reasons:
- This code is usually used by the person/her DataGrid. At least it can be used, so it must be placed in the form tag with runat = server.
- The error message is linkbutton instead of the DataGrid. Many careful friends may say that I have been using the DataGrid and where the linkbutton came from.
In fact, the real problem is that the above Code does not contain the lines.
Of course, if your DataGrid is not sorted and the button column is not used, there will be no problems.
To put it bluntly, linkbuttion is actually included in the header when you set the DataGrid to be sorted, so I want to set the order of the DataGrid to false.
In the same way, the above button columns, "edit", "delete", and so on also use linkbutton to make it invisible.
In fact, even more clearly, the linkbutton may be generated, or the output of other controls is not allowed.