Recently I want to sort out some word libraries, so I am too lazy to find them manually. I am afraid that my hand will be blank, so I decided to write it.ProgramComplete.
First, use the dataGridviewThe control is displayed on the page. The effect is as follows:
next we will gridview Excel , the method is as follows:
/// <Summary>
/// Export EXCEL from gridview
/// </Summary>
/// <Param name = "CTL"> Gridview Control ID </Param>
/// <Param name = "FILENAME"> Export Excel name </Param>
Private Void Toexcel (control CTL, String Filename)
{
Httpcontext. Current. response. charset = " UTF-8 " ;
Httpcontext. Current. response. contentencoding = System. Text. encoding. utf8;
Httpcontext. Current. response. contenttype = " Application/MS-Excel " ;
Httpcontext. Current. response. appendheader ( " Content-Disposition " , " Attachment; filename = " + "" + Filename );
CTL. Page. enableviewstate = False ;
System. Io. stringwriter TW = New System. Io. stringwriter ();
Htmltextwriter HW = New Htmltextwriter (TW );
CTL. rendercontrol (HW );
Httpcontext. Current. response. Write (TW. tostring ());
Httpcontext. Current. response. End ();
}
Add an event on the button to exportExcel. Note that becauseGridviewThere are paging and sorting settings. to display the complete data, you must cancel the paging sorting and export the data before resuming the settings.CodeAs follows:
Protected Void Btnexport_click ( Object Sender, eventargs E)
{
Gvword. allowpaging = False ;
Gvword. allowsorting = False ;
Display ();
Toexcel (gvword, " Word.xls " );
Gvword. allowsorting = True ;
Gvword. allowpaging = True ;
Display ();
}
However, an error is reported after running:
Type" Gridview "Control" Gridview1 "Must be placed Runat = Server .
Add rewrite method:
Public Override Void Verifyrenderinginserverform (Control)
{
// Base. verifyrenderinginserverform (control );
}
The effect is as follows:
Now, the program can help me sort it out, saving a lot of trouble.