Below is a summary of how to export the data of the gridview to excel, world, and PDF.
1. Export to word
Response. addheader ("content-disposition", "attachment?filename=export.doc ");
Response. cache. setcacheability (httpcacheability. nocache );
Response. contenttype = "application/vnd. Word ";
System. Io. stringwriter stringwrite = new system. Io. stringwriter ();
System. Web. UI. htmltextwriter htmlwrite = new htmltextwriter (stringwrite );
// Create a form to contain the grid
Htmlform FRM = new htmlform ();
GV. Parent. Controls. Add (FRM );
FRM. attributes ["runat"] = "server ";
FRM. Controls. Add (GV );
FRM. rendercontrol (htmlwrite );
// Gridview1.rendercontrol (HTW );
Response. Write (stringwrite. tostring ());
Response. End ();
2. Export to excel
String attachment = "attachment; filename=export.xls ";
Response. clearcontent ();
Response. addheader ("content-disposition", attachment );
Response. contenttype = "application/MS-excel ";
Stringwriter Sw = new stringwriter ();
Htmltextwriter HTW = new htmltextwriter (SW );
// Create a form to contain the grid
Htmlform FRM = new htmlform ();
GV. Parent. Controls. Add (FRM );
FRM. attributes ["runat"] = "server ";
FRM. Controls. Add (GV );
FRM. rendercontrol (HTW );
// Gridview1.rendercontrol (HTW );
Response. Write (SW. tostring ());
Response. End ();
3. Export to PDF
Now we need to use the open-source itext.
Using itextsharp. text;
Using itextsharp.text.pdf;
Using itextsharp.text.html;
Using itextsharp.text.html. simpleparser;
Response. contenttype = "application/pdf ";
Response. addheader ("content-disposition", "attachment?filename=export= ");
Response. cache. setcacheability (httpcacheability. nocache );
Stringwriter Sw = new stringwriter ();
Htmltextwriter hW = new htmltextwriter (SW );
Htmlform FRM = new htmlform ();
GV. Parent. Controls. Add (FRM );
FRM. attributes ["runat"] = "server ";
FRM. Controls. Add (GV );
FRM. rendercontrol (HW );
Stringreader sr = new stringreader (SW. tostring ());
Document required Doc = new document (pagesize. A4, 10f, 10f, 10f, 0f );
Htmlworker htmlparser = new htmlworker (workflow DOC );
Response writer. getinstance (Response doc, response. outputstream );
Using Doc. open ();
Htmlparser. parse (SR );
Using Doc. Close ();
Response. Write (Response DOC );
Response. End ();