ListView导出Excel

 

先引用:COM——》Microsoft.Excel
--------------------------------------------------------------------
public void ExportExcel(ListView lv)
  {
   if(lv.Items == null) return;
  
   string saveFileName = "";
   SaveFileDialog saveDialog = new SaveFileDialog();
   saveDialog.DefaultExt = "xls";
   saveDialog.Filter = "Excel文件|*.xls";
   saveDialog.FileName = DateTime.Now.ToString("yyyy-MM-dd");
   saveDialog.ShowDialog();
   saveFileName = saveDialog.FileName;
   if (saveFileName.IndexOf(":") < 0)
    return;
   //这里直接删除,因为saveDialog已经做了文件是否存在的判断
   if(File.Exists(saveFileName))File.Delete(saveFileName);
   Excel.Application xlApp = new Excel.Application();
   if (xlApp == null)
   {
    MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel");
    return;
   }
   Excel.Workbooks workbooks = xlApp.Workbooks;
   Excel.Workbook workbook = workbooks.Add(true);
   Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
   xlApp.Visible = false;
   //填充列
   for(int i=0;i<lv.Columns.Count;i++)
   {
    worksheet.Cells[1,i+1] = lv.Columns[i].Text.ToString();
    ((Excel.Range)worksheet.Cells[1,i+1]).Font.Bold = true;
   }
   //填充数据(这里分了两种情况,1:lv带CheckedBox,2:不带CheckedBox)
  
   //带CheckedBoxes
   if(lv.CheckBoxes == true)
   {
    int tmpCnt = 0;
    for(int i=0;i<lv.Items.Count;i++)
    {
     if(lv.Items[i].Checked == true)
     {
      for(int j=0;j<lv.Columns.Count;j++)
      {
       if(j==0)
       {
        worksheet.Cells[2+tmpCnt,j+1] = lv.Items[i].Text.ToString();
        ((Excel.Range)worksheet.Cells[2+tmpCnt,j+1]).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
       }
       else
       {
        worksheet.Cells[2+tmpCnt,j+1] = lv.Items[i].SubItems[j].Text.ToString();
        ((Excel.Range)worksheet.Cells[2+tmpCnt,j+1]).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
       }
      }
      tmpCnt++;
     }
    }
   }
   else  //不带Checkedboxe
   {
    for(int i=0;i<lv.Items.Count;i++)
    {
     for(int j=0;j<lv.Columns.Count;j++)
     {
      if(j==0)
      {
       worksheet.Cells[2+i,j+1] = lv.Items[i].Text.ToString();
       ((Excel.Range)worksheet.Cells[2+i,j+1]).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
      }
      else
      {
       worksheet.Cells[2+i,j+1] = lv.Items[i].SubItems[j].Text.ToString();
       ((Excel.Range)worksheet.Cells[2+i,j+1]).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
      }
     }
    }
   }
   object missing = System.Reflection.Missing.Value;
   try
   {
    workbook.Saved = true;
    workbook.SaveAs(saveFileName,Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing,false, false, Excel.XlSaveAsAccessMode.xlNoChange,missing, missing, missing, missing, missing);
   }
   catch (Exception e1)
   {
    MessageBox.Show("导出文件时出错,文件可能正被打开!/n" + e1.Message);
   }
   finally
   {
    xlApp.Quit();
    System.GC.Collect();
   }
   MessageBox.Show("导出成功!");
  }

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页