namespacedxhbskymdemo{ Public Partial classExcelForm:DevExpress.XtraEditors.XtraForm { PublicExcelform () {InitializeComponent (); } #regionExport Excel//Export button Private voidSbtndaochu_click (Objectsender, EventArgs e) { stringFileName ="";//the Excel file name to saveSaveFileDialog SFD =NewSaveFileDialog (); SfD. Filter="export Excel (*.xls) |*.xls";//Extended NameSfD. FileName ="Hebei Province project summary table";// if(SFD. ShowDialog () = =DialogResult.OK) {fileName=SFD. FileName; //ImportOutputexcel (fileName); } }
//How to export ExcelPrivate voidOutputexcel (stringSavefilepath) { BOOLIsshowexcel =false; DataTable DT=NewDataTable ();//Convert Database fetched data source to DataTable if(dt = =NULL) { return; } if(dt. Rows.Count = =0) { return; } Missing Miss=Missing.Value; Excel.Application xlapp=NewExcel.Application (); if(xlapp = =NULL) {xtramessagebox.show ("Make sure your computer is installed excel! ","Prompt Information", MessageBoxButtons.OK, messageboxicon.information); return; } //Xlapp.usercontrol = true;Excel.Workbooks Workbooks =Xlapp.workbooks; //Excel.Workbook Workbook = Workbooks.Add (Excel.XlWBATemplate.xlWBATWorksheet);//Create a newExcel.Workbook Workbook = Workbooks.Add (System.AppDomain.CurrentDomain.BaseDirectory +"excel\\ Project summary table. xls");//Create a new workbook based on an existing Excel templateExcel.Worksheet Worksheet = (excel.worksheet) workbook.worksheets[1];//get Sheet1 if(WorkSheet = =NULL) {xtramessagebox.show ("Make sure your computer is installed excel! ","Prompt Information", MessageBoxButtons.OK, messageboxicon.information); return; } Try{excel.range Range=NULL; Xlapp.visible= Isshowexcel;//If True, the Excel interface will be displayed when exporting intTotalCount =dt. Rows.Count; worksheet.cells[1,1] ="Shijiazhuang City, Hebei Province project summary table";//Export Title//Write Value for(inti =0; i < dt. Rows.Count; i++) {worksheet.cells[i+4,1] = dt. rows[i]["Xmxh"];//Item Number//worksheet.cells[5,1]= "";//represents the cell coordinates of the intersection of line fifth and the first column
4 2] = dt. rows[i]["xmmc"]; // Project Name ((Excel.Range) worksheet.cells[i+4, 2]). ColumnWidth = 12;//Setting column widths
worksheet.cells[i+4,3] = dt. rows[i]["BZ"];//Notes} worksheet.saveas (Savefilepath, Type.Missing, Type. Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Workbooks.close (); } Catch(Exception ex) {xtramessagebox.show ("Excel export failed with error:"+ ex. Message,"Prompt Information", MessageBoxButtons.OK, messageboxicon.information); xlApp.Quit (); Regexpre.killexcelprocess (); } finally{xlapp.quit (); Regexpre.killexcelprocess (); } } #endregion }}
C # Winform Excel export, export data based on Excel template