/// <summary>
/// 执行ListView到Excel导出
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void dcEXCELToolStripMenuItem_Click(object sender, EventArgs e)
{
string filename = DateTime.Now.ToString(“yyyyMMddHHmmss”);
string excelFilePath = string.Format(“{0}\\Excel-{1}.xls”, Directory.GetCurrentDirectory(), filename);
if (File.Exists(excelFilePath))
{
File.Delete(excelFilePath);
}
this.LvtoExcel(this.listView1, excelFilePath);
MessageBox.Show(“导出结束!”);
}
/// <summary>
/// 从ListView到Excel具体方法
/// </summary>
/// <param name=”lv”></param>
/// <param name=”filename”></param>
private void LvtoExcel(ListView lv, string filename)
{
int rownum = lv.Items.Count;
if (rownum == 0 || string.IsNullOrEmpty(filename))
{
MessageBox.Show(“没有记录”);
return;
}
int columnnum = lv.Items[0].SubItems.Count;
int rowindex = 1;
int columnindex = 0;
if (rownum > 0)
{
Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();
if (excelapp == null)
{
MessageBox.Show(“无法创建EXCEL对象,可能你的系统没有安装EXCEL”);
return;
}
//因为使用COM库,因此有许多变量用Nothing代替
Object Nothing = Missing.Value;
Workbook wb = excelapp.Workbooks.Add(Nothing);
Microsoft.Office.Interop.Excel.Worksheet ws = wb.Sheets[1];
//将ListView的列名导入Excel第一行
foreach (ColumnHeader lc in lv.Columns)
{
columnindex++;
ws.Cells[rowindex, columnindex] = lc.Text;
}
//将ListView的值导入Excel
for (int i = 0; i < rownum; i++)
{
rowindex++;
columnindex = 0;
for (int j = 0; j < columnnum; j++)
{
columnindex++;
//注意这个在导出是加”\t”的目的是避免导出的数据显示为科学计数法
ws.Cells[rowindex, columnindex] = Convert.ToString(lv.Items[i].SubItems[j].Text) + “\t”;
}
}
wb.SaveAs(filename, XlFileFormat.xlWorkbookNormal, Nothing, Nothing, Nothing, Nothing, XlSaveAsAccessMode.xlNoChange, Nothing, Nothing, Nothing, Nothing, Nothing);
wb.Close(Nothing, Nothing, Nothing);
excelapp.Quit();
}
}