Often used in Database SystemsExcel, Sometimes you need to useExcelAs a data source, sometimes you need to use the queried dataExcelWill be used continuously.Excel .....
First load the reference:
UsingMicrosoft. Office. InterOP. Excel;
Using Excelapplication= Microsoft. Office. InterOP. Excel.Application;
Note: If you have previously loaded using system. Data, note the following:
Instead of defining datatable table directly, instead of system. Data.Datatable tableOr perform another conversion, becauseExcelapplicationThere are also datatable classes,
Public static void dotoexcel (system. Data. datatable table)
{
Try
{
Excelapplication Excel = new excelapplication ();
Int rowindex = 1;
Int colindex = 0;
Excel. application. workbooks. Add (true );
Foreach (datacolumn Col in table. columns)
{
Colindex ++;
Excel. cells [1, colindex] = col. columnname;
}
Foreach (datarow row in table. Rows)
{
Rowindex ++;
Colindex = 0;
Foreach (datacolumn Col in table. columns)
{
Colindex ++;
Excel. cells [rowindex, colindex] = row [col. columnname]. tostring ();
}
}
Excel. Visible = false;
Savefiledialog Sf = new savefiledialog ();
SF. addextension = true;
SF. Filter = "Excel 2003 (*. xls) | *. xls |All files| *.*";
SF. Title ="ExportExcelSave";
If (SF. showdialog () = dialogresult. OK)
{
String filename = SF. filename;
Excel. activeworkbook. saveas (filename, Microsoft. office. interOP. excel. xlfileformat. xlexcel9795, null, null, false, false, Microsoft. office. interOP. excel. xlsaveasaccessmode. xlnochange, null, null );
Excel. Quit ();
Excel = NULL;
GC. Collect ();
MessageBox. Show ("Exported successfully!");
}
}
Catch (exception ex)
{
MessageBox. Show ("Export failed!");
Writelogtxt ("dotoexcel", Ex. Message );
}
}
# Endregion
}
In the preceding exampleSystem. Data. datatable tableConvertExcel,Col. columnnameAll will be the default, it is best to operateSystem. Data. datatable tableTime conversion, including statistical rows......