Try
... {String filename;
Savefiledialog SFD = new savefiledialog ();
SFD. Title = "select the path to store exported Excel files ";
SFD. Filter = "Excel document (*. xls) | *. xls ";
// SFD. openfile ();
SFD. showdialog ();
If (SFD. filename! = "")
...{
If (SFD. filename. lastindexof (". xls") <= 0)
...{
SFD. filename = SFD. filename + ". xls ";
}
Filename = SFD. filename;
If (system. Io. file. exists (filename ))
...{
System. Io. file. Delete (filename );
}
Excel. applicationclass xlapp = new excel. applicationclass ();
If (xlapp = NULL)
...{
MessageBox. Show ("an Excel object cannot be created. Excel may not be installed on your machine ");
Return;
}
Excel. workbooks = xlapp. workbooks;
Excel. Workbook workbook = workbooks. Add (Excel. xlwbatemplate. xlwbatworksheet );
Excel. worksheet = (Excel. worksheet) Workbook. worksheets [1];
Datatable dt1 = (datatable) datagrid2.datasource;
Float percent = 0;
Long rowread = 0;
If (dt1 = NULL)
...{
MessageBox. Show ("1 ");
Return;
}
Long totalcount = dt1.rows. count;
This. progressbar1.visible = true;
For (INT I = 0; I <dt1.rows. Count; I ++)
...{
This. progressbar1.value = I;
For (Int J = 0; j <dt1.columns. Count; j ++)
...{
If (I = 0)
...{
Worksheet. cells [1, J + 1] = dt1.columns [J]. columnname;
}
Worksheet. cells [I + 2, J + 1] = dt1.rows [I] [J]. tostring ();
}
Rowread ++;
Percent = (float) (100 * rowread)/totalcount;
This. progressbar1.text = "exporting data [" + percent. tostring ("0.00") + "%]...";
}
This. progressbar1.visible = false;
Workbook. Saved = true;
Workbook. savecopyas (filename );
System. runtime. interopservices. Marshal. releasecomobject (worksheet );
Worksheet = NULL;
System. runtime. interopservices. Marshal. releasecomobject (workbook );
Workbook = NULL;
Workbooks. Close ();
System. runtime. interopservices. Marshal. releasecomobject (workbooks );
Workbooks = NULL;
Xlapp. Quit ();
System. runtime. interopservices. Marshal. releasecomobject (xlapp );
Xlapp = NULL;
MessageBox. Show ("Excel exported! "," Prompt ", messageboxbuttons. OK, messageboxicon. information );
// Button2_click (null, null );
}
}
Catch (exception ex)
...{
MessageBox. Show ("An error occurred while exporting excel! "+ Ex. message," error ", messageboxbuttons. OK, messageboxicon. information );
}