Use gembox. excellite. DLL to exit the Excel environment and export the datagridview data to an Excel file.
Public Void Datagridview2excel_gembox (datagridview dgv ){ # Region Pre-export judgment // The number of rows must be greater than 0. If (Dgv. Rows. Count <= 0 ) {MessageBox. Show ( " No data is available for export! " , " Prompt " , Messageboxbuttons. OK, messageboxicon. information ); Return ;} // The number of columns must be greater than 0. If (Dgv. Columns. Count <= 0 ) {MessageBox. Show ( " No data is available for export! " , " Prompt " , Messageboxbuttons. OK, messageboxicon. information ); Return ;} // The number of rows cannot exceed 65536 If (Dgv. Rows. Count> 65536 ) {MessageBox. Show ( " Too many data records (up to 65536 records) cannot be saved! " , " Prompt " , Messageboxbuttons. OK, messageboxicon. information ); Return ;} // The number of Columns cannot exceed 256 If (Dgv. Columns. Count> 256 ) {MessageBox. Show ( " Too many data records (up to 256 columns allowed) cannot be saved! " , " Prompt " , Messageboxbuttons. OK, messageboxicon. information ); Return ;} # Endregion Savefiledialog DLG = New Savefiledialog (); DLG. Filter = " Excel files (*. xls) | *. xls " ; DLG. filterindex = 0 ; DLG. restoredirectory = True ; DLG. createprompt = False ; DLG. Title = " Export as an Excel file " ; If (DLG. showdialog () = Dialogresult. OK) {excelfile = New Excelfile (); excelworksheet Sheet = Excelfile. worksheets. Add ( " Account " ); Try { // Table header written to excel For ( Int I = 0 ; I <dgv. Columns. Count; I ++ ) {Sheet. cells [ 0 , I]. value = Dgv. Columns [I]. headertext ;} // Write table data to excel For ( Int I = 0 ; I <dgv. Rows. Count; I ++ ) {Maid row = Dgv. Rows [I]; For ( Int J = 0 ; J <row. cells. Count; j ++ ) {Sheet. cells [I + 1 , J]. value = Row. cells [J]. Value ;}} excelfile. savexls (DLG. filename );} Catch (Exception ex) {MessageBox. Show (ex. Message, " Warning " , Messageboxbuttons. OK, messageboxicon. Warning ); Return ;} MessageBox. Show (DLG. filename + " \ N exported! " , " Prompt " , Messageboxbuttons. OK, messageboxicon. Information );}}
Download gembox. excellite. dll