【问题标题】:Question: How do I export a C# ListView Winform control to a Microsoft Excel Workbook问题:如何将 C# ListView Winform 控件导出到 Microsoft Excel 工作簿
【发布时间】:2022-01-12 15:24:21
【问题描述】:
我来到 SO 寻找一个通用的解决方案,将 ListView 控件导出到带有单个工作表的 Microsoft Excel 工作簿
注意事项
- 我想将新工作簿中的工作表数配置为 1
- 我想告诉 excel 单元格重新计算是手动的。
我找到了一些潜在的部分解决方案。我没有找到任何我认为有用的东西作为起点。
我正在回答我自己的问题。谢谢,我希望它可以帮助别人。
【问题讨论】:
标签:
c#
excel
winforms
listview
export
【解决方案1】:
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;
}
}