Private voidExport Exceltoolstripmenuitem_click (Objectsender, EventArgs e) { if(Dgvdata.rowcount >0) { varSaveFileDialog1 =NewSaveFileDialog {Filter=@"Excel File (*.xls,*.xlsx) |*.xls;*.xlsx", Restoredirectory=true }; if(Savefiledialog1.showdialog () = =DialogResult.OK) {exportexcel (Savefiledialog1.filename, Dgvdata,2); } } Else{MessageBox.Show (@"data is empty !!"); } }/// <summary> ///Export Excel Methods/// </summary> /// <param name= "FileName" >Export Path</param> /// <param name= "GridView" >Data Source</param> /// <param name= "num" >starting from the first few columns</param> Private voidExportexcel (stringFileName, DataGridView GridView,intnum) { if(Filename.indexof (":") <0)return;//it was canceled.Microsoft.Office.Interop.Excel.Application xlapp =NewMicrosoft.Office.Interop.Excel.Application (); if(xlapp = =NULL) {MessageBox.Show (@"Unable to create Excel object, may not have Excel installed on your machine"); return; } 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 intA =1, B =1; for(vari =0; i < Gridview.rowcount; i++) { if(i = =0) { for(varj = num; J < GridView.Columns.Count; J + +) {worksheet. cells[1, A] =Gridview.columns[j]. HeaderText; A++; } } for(varj = num; J < GridView.Columns.Count; J + +) {worksheet. Cells[i+2, b] =Gridview.rows[i]. CELLS[J]. Value; b++; } b=1; System.Windows.Forms.Application.DoEvents (); } worksheet. Columns.EntireColumn.AutoFit ();//self-adapting column widths if(FileName! ="") { Try{workbook. Saved=true; Workbook. SaveCopyAs (FileName); } Catch(Exception ex) {MessageBox.Show (@"file export error, file may be open! "+Ex. Message); }} xlapp.quit (); Gc. Collect ();//forcibly destroyedMessageBox.Show (@"file export success!!",@"Tips", MessageBoxButtons.OK, messageboxicon.information); }
Winform DataGridView Export Excel