ListView中的数据表格写入Excel中

时间:2023-03-09 16:34:43
ListView中的数据表格写入Excel中

    SaveFileDialog sfd = new SaveFileDialog();

    sfd.DefaultExt = "xls";

    sfd.Filter = "Excel文?件t(*.xls)|*.xls";

   if (sfd.ShowDialog() == DialogResult.OK)

    {

     DoExport(this.listView1, sfd.FileName);

   }

    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("无法创建excel对象,可能您系统没有安装excel");

   return;

  }

   xlApp.DefaultFilePath = "";

    xlApp.DisplayAlerts = true;

   xlApp.SheetsInNewWorkbook = 1;

    Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);

   //将ListView中的列名导入Excel表第一行

   foreach (ColumnHeader dc in listView.Columns)

   {

     columnIndex++;

     xlApp.Cells[rowIndex, columnIndex] = dc.Text;

    }

    for (int i = 0; i < rowNum; i++)

  {

     rowIndex++;

     columnIndex = 0;

     for (int j = 0; j < columnNum; j++)

    {

        columnIndex++;

          //注意这个在导出的时候加了"\t"的目的是避免导出的数据显示为科学计数法,可以放在每行的首尾

           xlApp.Cells[rowIndex, columnIndex] = Convert.ToString(listView.Items[i].SubItems[j].Text) + "\t";

       }

    }

    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.Close();

    xlBook = null;

   MessageBox.Show("OK");

   }

   }