In winform development, you often need to export the data displayed in the DataGrid to various file formats. Take exporting excel as an example:
1. inherit from the net DataGrid
Public class datagridex: system. Windows. Forms. DataGrid
2. Add an Excel reference
3. Compile the export Method
Public bool exportexcel ()
{
Return exportexcel ("");
}
Public bool exportexcel (string p_reportname)
{
If (this. tablestyles. Count = 0) return false;
Datagridtablestyle Ts = This. tablestyles [0];
// Create a header -- leewenjie 2006-11-21
Excel. Application xlapp = new excel. applicationclass ();
Excel. Workbook xlbook = xlapp. workbooks. Add (true );
Excel. worksheet xlsheet = (Excel. worksheet) xlbook. worksheets [1];
Excel. Range = xlsheet. get_range (xlapp. cells [1, 1], xlapp. cells [1, ts. gridcolumnstyles. Count]);
Range. mergecells = true;
Xlapp. activecell. formular1c1 = p_reportname;
Xlapp. activecell. Font. size = 20;
Xlapp. activecell. Font. Bold = true;
Xlapp. activecell. horizontalalignment = excel. constants. xlcenter;
// Create a column header -- leewenjie 2006-11-21
Int colindex = 0;
Int rowindex = 2;
Foreach (maid Cs IN ts. gridcolumnstyles)
{
Colindex ++;
Xlsheet. cells [rowindex, colindex] = cs. headertext;
}
// Output from Excel Based on the content displayed in the grid
// Assign a value to a cell
Int rowcount = This. bindingcontext [This. datasource, this. datamember]. count;
For (INT I = 0; I <rowcount; I ++)
{
Rowindex ++;
Int colcount = ts. gridcolumnstyles. count;
For (colindex = 1; colindex <= colcount; colindex ++)
{
Xlsheet. cells [rowindex, colindex] = This [I, colIndex-1];
}
Application. doevents ();
}
Xlbook. Saved = true;
Xlbook. savecopyas ("D: // fly" + datetime. Now. tostring ("yyyymmdd") + ". xls ");
Xlapp. Quit ();
GC. Collect ();
Return true;
}
Development Environment:
Vs. NET 2003
Defect: The export speed is slow. I tried to use multiple threads, but the effect is not satisfactory.
It takes about 6 minutes for 8000 pieces of data. Please give me more advice!
**************************************