Private void export data _ Click (object sender, EventArgs e) { ExportToExecl (); } /// <Summary> /// Export data /// </Summary> Public void ExportToExecl () { System. Windows. Forms. SaveFileDialog sfd = new SaveFileDialog (); Sfd. DefaultExt = "xls "; Sfd. Filter = "Excel file (*. xls) | *. xls "; If (sfd. ShowDialog () = DialogResult. OK) { DoExport (this. lstPostion, sfd. FileName ); } } /// <Summary> /// Specific export method /// </Summary> /// <Param name = "listView"> ListView </param> /// <Param name = "strFileName"> name of the exported file </param> Private void DoExport (ListView listView, string strFileName) { Int rowNum = listView. Items. Count; Int columnNum = listView. Items [0]. SubItems. Count; Int rowIndex = 1; Int columnIndex = 0; If (rowNum = 0 | string. IsNullOrEmpty (strFileName )) { Return; } If (rowNum> 0) { Microsoft. Office. Interop. Excel. Application xlApp = new Microsoft. Office. Interop. Excel. ApplicationClass (); If (xlApp = null) { MessageBox. Show ("an excel object cannot be created, or excel is not installed in your system "); Return; } XlApp. DefaultFilePath = ""; XlApp. DisplayAlerts = true; XlApp. SheetsInNewWorkbook = 1; Microsoft. Office. Interop. Excel. Workbook xlBook = xlApp. Workbooks. Add (true ); // Import the column name of ListView to the first row of the Excel table Foreach (ColumnHeader dc in listView. Columns) { ColumnIndex ++; XlApp. Cells [rowIndex, columnIndex] = dc. Text; } // Import Data in ListView to Excel For (int I = 0; I <rowNum; I ++) { RowIndex ++; ColumnIndex = 0; For (int j = 0; j <columnNum; j ++) { ColumnIndex ++; // Note that the purpose of adding "t" to the export is to prevent the exported data from being displayed as scientific notation. It can be placed at the beginning and end of each line. XlApp. Cells [rowIndex, columnIndex] = Convert. ToString (listView. Items [I]. SubItems [j]. Text) + "t "; } } // The exception must be noted that strFileName and Excel are used. xlFileFormat. when xlExcel9795 is saved, an error is returned when your Excel versions are not 95, 97, but 2003 and 2007. The exception is HRESULT: 0x800A03EC. The solution is to replace strFileName with 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 "); } } |