Need to reference
Public voidexporttoexecl () {System.Windows.Forms.SaveFileDialog sfd=NewSaveFileDialog (); SfD. DefaultExt="xls"; SfD. Filter="Excel File (*.xls) |*.xls"; if(SFD. ShowDialog () = =DialogResult.OK) {Doexport ( This. ListView1, SFD. FileName); } } /// <summary> ///method of specific export/// </summary> /// <param name= "ListView" >ListView</param> /// <param name= "strFileName" >the file name to export to</param> Private voidDoexport (ListView ListView,stringstrFileName) { intRowNum =ListView.Items.Count; intColumnnum = listview.items[0]. Subitems.count; intRowIndex =1; intColumnIndex =0; if(RowNum = =0||string. IsNullOrEmpty (strFileName)) {return; } if(RowNum >0) {Microsoft.Office.Interop.Excel.Application xlapp=NewMicrosoft.Office.Interop.Excel.ApplicationClass (); if(xlapp = =NULL) {MessageBox.Show ("cannot create an Excel object, your system may not have Excel installed"); return; } Xlapp.defaultfilepath=""; Xlapp.displayalerts=true; Xlapp.sheetsinnewworkbook=1; Microsoft.Office.Interop.Excel.Workbook Xlbook= XLAPP.WORKBOOKS.ADD (true); //Import the column name of the ListView into the first row of the Excel table foreach(ColumnHeader DCinchlistview.columns) {columnindex++; Xlapp.cells[rowindex, ColumnIndex]=DC. Text; } //import data from a ListView into Excel for(inti =0; i < RowNum; i++) {RowIndex++; ColumnIndex=0; for(intj =0; J < Columnnum; J + +) {columnindex++; //Note that the purpose of adding "\ t" when exporting is to avoid displaying the exported data as scientific notation. Can be placed at the end of each line. Xlapp.cells[rowindex, ColumnIndex]= Convert.ToString (Listview.items[i]. SUBITEMS[J]. Text) +"\ t"; } } //the exception needs to be explained is that when using strfilename,excel.xlfileformat.xlexcel9795 save mode when your Excel version is not 95, 97 instead of 2003, 2007 when the export will report an error: Exception from Hresult:0x800a03ec. The solution is to switch to strFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal. Xlbook.saveas (strFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Xlapp=NULL; Xlbook=NULL; MessageBox.Show ("OK"); } }
C#winfrom ListView Data into Excel