You only need to pass in the name of DataGridView.
1 //export Excel () method2 Public voidToexcel (DataGridView DataGridView)3 {4 //instantiate a Excel.Application object5Microsoft.Office.Interop.Excel.Application Excel =NewMicrosoft.Office.Interop.Excel.Application ();6 7 if(Excel = =NULL)8 {9Umessageboxwarning ("cannot create an Excel object, your computer may not be installed excel!");Ten return; One } A Try - { - //no data, no execution. the if(DataGridView.Rows.Count = =0) - return; - - //let background execution be set to invisible, true if you see Open an Excel, then data is written in +Excel. Visible =true; - + //Add a new workbook, workbook is directly saved, will not pop up the Save dialog box, plus application will pop up the Save dialog box, the value of false will error AExcel. APPLICATION.WORKBOOKS.ADD (true); at //Generate column header names in Excel - for(inti =0; i < DataGridView.Columns.Count; i++) - { - if(Datagridview.columns[i]. Visible = =true) - { -Excel. cells[1, i +1] =Datagridview.columns[i]. HeaderText; in } - to } + //save data from the current page of DataGridView in Excel - for(inti =0; I < DataGridView.Rows.Count-1; i++) the { * application.doevents (); $ for(intj =0; J < DataGridView.Columns.Count; J + +)Panax Notoginseng { - if(Datagridview.columns[j]. Visible = =true) the { + if(Datagridview[j, I]. ValueType = =typeof(string)) A { theExcel. Cells[i +2, J +1] ="'"+datagridview[j, I]. Value.tostring (); + } - Else $ { $Excel. Cells[i +2, J +1] =datagridview[j, I]. Value.tostring (); - } - } the - }Wuyi } the //set up a query prompt to suppress pop-up saves and overrides - //... Wu //Make sure the Excel process is closed - Excel. Quit (); AboutExcel =NULL; $Gc. Collect ();//If you do not use this statement causes the Excel process to quit gracefully and exit normally after use -Umessageboxnone ("The file has been successfully exported! "); - } - Catch(Exception ex) A { + MessageBox.Show (ex. Message); the } - $}
C#winform in DataGridView Export Excel