简体   繁体   中英

Question: How do I export a C# ListView Winform control to a Microsoft Excel Workbook

I came to SO looking for a generic solution to export a ListView control to a Microsoft Excel Workbook with a single sheet

Notes

  1. I want to configure number of sheets in a new workbook to 1
  2. I want to tell excel that cell recalculation is manual.

I found a few potential partial solutions. I didn't find anything I found useful as a starting point.

I am answering my own question. Thanks and I hope it helps someone else.

 using System; using System.Reflection; using System.Windows.Forms; // Add a COM reference to "Microsoft Excel ##.# Object" static class ExportListView { static public bool ExportToExcel(ListView lv, bool bColHdr = true) { bool bRet = true; try { Cursor.Current = Cursors.WaitCursor; Microsoft.Office.Interop.Excel.Application oXL; Microsoft.Office.Interop.Excel._Workbook oWB; Microsoft.Office.Interop.Excel._Worksheet oSheet; try { oXL = new Microsoft.Office.Interop.Excel.Application { SheetsInNewWorkbook = 1 }; oWB = oXL.Workbooks.Add(Missing.Value); oXL.Calculation = Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationManual; oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.Sheets[1]; int iCol = -1; for (iCol = 1; iCol <= lv.Columns.Count && bColHdr; iCol++) oSheet.Cells[1, iCol] = lv.Columns[iCol - 1].Text; for (int iRow = 1; iRow <= lv.Items.Count; iRow++) { for (iCol = 1; iCol <= lv.Items[iRow - 1].SubItems.Count; iCol++) oSheet.Cells[bColHdr? iRow + 1: iRow, iCol] = lv.Items[iRow - 1].SubItems[iCol - 1].Text; } try { oWB.Worksheets[1].Delete(); } catch { Console.WriteLine("Error Deleting Sheet1"); } for (int iSheet = 1; iSheet <= oWB.Sheets.Count; iSheet++) oWB.Sheets[iSheet].Columns.AutoFit(); oWB.Worksheets[1].Activate(); oXL.Visible = true; oXL.UserControl = true; } catch (Exception ex) { MessageBox.Show(ex.Message); bRet = false; } } catch (Exception) { } finally { Cursor.Current = Cursors.Default; } return bRet; } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM