// Export the Excel file
Private void exportexcel ()
{
Dataset DS = dtsselect; // Data Source
If (DS = NULL) return;
String savefilename = "";
Bool filesaved = false;
Savefiledialog savedialog = new savefiledialog ();
Savedialog. defaultext = "xls ";
Savedialog. Filter = "Excel file | *. xls ";
Savedialog. filename = "sheet1 ";
Savedialog. showdialog ();
Savefilename = savedialog. filename;
If (savefilename. indexof (":") <0) return; // canceled
Excel. Application xlapp = new excel. Application ();
If (xlapp = NULL)
{
MessageBox. Show ("an Excel object cannot be created, maybe your computer has not installed excel ");
Return;
}
Excel. workbooks = xlapp. workbooks;
Excel. Workbook workbook = workbooks. Add (Excel. xlwbatemplate. xlwbatworksheet );
Excel. worksheet = (Excel. worksheet) Workbook. worksheets [1]; // get sheet1
// Write Fields
For (INT I = 0; I <Ds. Tables [0]. Columns. Count; I ++)
{
Worksheet. cells [1, I + 1] = Ds. Tables [0]. Columns [I]. columnname;
}
// Write Value
For (INT r = 0; r <Ds. Tables [0]. Rows. Count; r ++)
{
For (INT I = 0; I <Ds. Tables [0]. Columns. Count; I ++)
{
Worksheet. cells [R + 2, I + 1] = Ds. Tables [0]. Rows [r] [I];
}
System. Windows. Forms. application. doevents ();
}
Worksheet. Columns. entirecolumn. autofit (); // adaptive column width.
If (cmbxtype. Text! = "Notification ")
{
Excel. Range Rg = worksheet. get_range (worksheet. cells [2, 2], Worksheet. cells [Ds. Tables
[0]. Rows. Count + 1, 2]);
RG. numberformat = "00000000 ";
}
If (savefilename! = "")
{
Try
{
Workbook. Saved = true;
Workbook. savecopyas (savefilename );
Filesaved = true;
}
Catch (exception ex)
{
Filesaved = false;
MessageBox. Show ("An error occurred while exporting the file. The file may be opened! \ N "+ ex. Message );
}
}
Else
{
Filesaved = false;
}
Xlapp. Quit ();
GC. Collect (); // forcibly destroy
If (filesaved & system. Io. file. exists (savefilename) system. Diagnostics. process. Start
(Savefilename); // enable exce