Public stringExportexcel (DataSet ds,stringsavefilename) { Try { if(ds = =NULL) return "the database is empty"; BOOLfilesaved =false; Microsoft.Office.Interop.Excel.Application xlapp=NewMicrosoft.Office.Interop.Excel.Application (); if(xlapp = =NULL) { return "Unable to create Excel object, may not have Excel installed on your machine"; } Microsoft.Office.Interop.Excel.Workbooks Workbooks=Xlapp.workbooks; Microsoft.Office.Interop.Excel.Workbook Workbook=workbooks. ADD (Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet Worksheet= (Microsoft.Office.Interop.Excel.Worksheet) workbook. worksheets[1];//get Sheet1//Write Fields for(inti =0; I < DS. tables[0]. Columns.count; i++) {worksheet. cells[1, i +1] = ds. tables[0]. Columns[i]. ColumnName; } //Write Value for(intR =0; R < DS. tables[0]. Rows.Count; r++) { for(inti =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 ();//column widths are self-adapting. 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 being opened! \ n"+Ex. Message); } } Else{filesaved=false; } xlapp.quit (); Gc. Collect ();//forcibly destroyed if(filesaved && System.IO.File.Exists (savefilename)) System.Diagnostics.Process.Start (Savefilename);//Open Excel return "successfully saved to Excel"; } Catch(Exception ex) {returnEx. ToString (); } }
SQL data is saved to an Excel file