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

          }

       }

  • 相关阅读:
    【转帖】分享一个迅为4412开发板OTG烧录批处理文件
    4412开发板图像识别项目-移植百度AI依赖库curl(二)
    4412开发板图像识别项目-初识人工智能(一)
    迅为4412开发板门禁系统项目的硬件框架扩展
    Linux开发板
    迅为i.MX6Q开发板用于中3D打印设备
    迅为I.MX6ULL开发板移植Linux5.4内核教程
    嵌入式开发与学习——迅为IMX6ULL开源硬件开发板
    迅为4412开发板实战机车导航-GPS定位系统
    迅为IMX6ULL开发板可外接模块丰富,兼容性强
  • 原文地址:https://www.cnblogs.com/zhanglei93/p/4782096.html
Copyright © 2011-2022 走看看