zoukankan      html  css  js  c++  java
  • 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++;

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

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

                      }

                 }

                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");

          }

       }

  • 相关阅读:
    pythonday06数据类型(四)
    pythonday05数据类型(三)
    pythonday04数据类型(二)
    pythonday03数据类型(一)
    Apollo自动驾驶实践——第0讲:导论
    图论学习:生成树的Matrix-tree定理
    2020杭电多校6 Expectation
    2020牛客暑期多校第九场 B Groundhog and Apple Tree
    图论:二分图最大权匹配KM算法
    第十章 百度Apollo实战
  • 原文地址:https://www.cnblogs.com/zhanglei93/p/4782096.html
Copyright © 2011-2022 走看看