博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c# listview导出excel文件
阅读量:6195 次
发布时间:2019-06-21

本文共 3802 字,大约阅读时间需要 12 分钟。

首先在工程中需要添加对Microsoft Excel office 11.0 object的引用

生成excel的类代码如下

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace LvwToExcel
{
    class CExcel
    {  
        /// <summary>
        /// 导出Excel文件
        /// </summary>
        /// <param name="lvwShow">数据源</param>
        /// <param name="strExcelTitle">Excel文件名</param>
        public void LvwToExcel(ListView lvwShow,string strExcelName)
        {
            int row = lvwShow.Items.Count;//listview行数
            int col = lvwShow.Items[0].SubItems.Count;//listview列数
        
            if (row == 0 || string.IsNullOrEmpty(strExcelName))
            {
                return;
            }
            if (row > 0)
            {
                Microsoft.Office.Interop.Excel._Application ExcelApp = new Microsoft.Office
                .Interop.Excel.Application();
                if (ExcelApp == null)
                {
                    MessageBox.Show("无法创建Excel对象,可能你的系统没有安装Excel!!!");
                    return;
                }
                object m_objOpt = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Excel.Workbooks ExcleBooks = (Microsoft.Office.Interop.Excel.Workbooks)ExcelApp.Workbooks;
                Microsoft.Office.Interop.Excel._Workbook ExcleBook=(Microsoft.Office.Interop.Excel._Workbook )(ExcleBooks.Add(m_objOpt));
                Microsoft.Office.Interop.Excel._Worksheet ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcleBook.ActiveSheet;
                ExcelApp.Visible = true;
                //读取listview表头做为excel列标题,listview中,行和列的下标索引都是从0开始
                for (int i = 1; i <= col; i++)
                {
                    ExcelSheet.Cells[1, i] = lvwShow.Columns[i-1].Text;
                }
                for (int i = 0; i <row; i++)
                {  
                    ExcelSheet.Cells[i+2, 1] = lvwShow.Items[i].Text;//获取所有行第一列的值

                    for (int j = 1; j < col; j++)

                    {
                        ExcelSheet.Cells[i+2, j+1] = lvwShow.Items[i].SubItems[j].Text;//获取某一行某一列的值
                    }
                }
                ExcleBook.SaveAs(strExcelName);
                //ExcelApp.Quit();//退出excel
                ExcelApp = null;
                ExcelSheet = null;
                ExcleBooks = null;
                ExcleBook = null;
            }
        }
        /// <summary>
        /// 保存Excel文件
        /// </summary>
        public void ExportExcel(ListView lvwShow)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.DefaultExt = "xls";
            sfd.Filter = "Excel文件(*.xls)|*.xls";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                LvwToExcel(lvwShow,sfd.FileName);
            }
        }
    }
}

二winform窗体中添加一个Listview控件具体代码如下

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace LvwToExcel
{
    public partial class FrmToExcel : Form
    {  
        private  SqlConnection con=new SqlConnection();

        public FrmToExcel()

        {
            InitializeComponent();
        }
        public void initLvw()
        {
            listViewShow.FullRowSelect = true;
            listViewShow.GridLines = true;
            listViewShow.MultiSelect = false;
            listViewShow.View = View.Details;
            listViewShow.HideSelection = false;
            listViewShow.Columns.Add("1", 100, HorizontalAlignment.Center);
            listViewShow.Columns.Add("2", 100, HorizontalAlignment.Center);
            listViewShow.Columns.Add("3", 100, HorizontalAlignment.Center);
            listViewShow.Columns.Add("4", 100, HorizontalAlignment.Center);
          
        }

        private void FrmToExcel_Load(object sender, EventArgs e)

        {
            initLvw();
            //连接数据库
            string sqlConnect = "initial catalog=数据库名;server='服务器名';uid=sa;pwd=密码";
            con = new SqlConnection(sqlConnect);
            con.Open();
            SqlDataReader DR;
            SqlCommand sqlcom = new SqlCommand();
            sqlcom.Connection = con;
            string sqlStr = "select top 5 1,2,3,4 from item";
            sqlcom.CommandText = sqlStr;
            DR = sqlcom.ExecuteReader();
            LvwShowTable(DR);

        }

               private void LvwShowTable(SqlDataReader dr)
        {  
            //读取表中记录
            while (dr.Read())
            {
                ListViewItem li = new ListViewItem();
                li.SubItems.Clear();
                li.SubItems[0].Text = dr["1"].ToString()==""?"NULL":dr["1"].ToString();
                li.SubItems.Add(dr["2"].ToString() == "" ? "NULL" : dr["2"].ToString());
                li.SubItems.Add(dr["3"].ToString()==""?"NULL":dr["3"].ToString());
                li.SubItems.Add(dr["4"].ToString()==""?"NULL":dr["4"].ToString());
                listViewShow.Items.Add (li);
            }
        }

               private void btnToExcel_Click(object sender, EventArgs e)

               {
                   CExcel excel = new CExcel();
                   excel.ExportExcel(listViewShow);
               }

    }

}

 

 

转载地址:http://afyca.baihongyu.com/

你可能感兴趣的文章
NSOperation 开发
查看>>
二叉排序树
查看>>
毕业随想(转载)
查看>>
8086汇编——课堂笔记整理4
查看>>
小程序开发之改变data中数组或对象的某一属性值
查看>>
asp.net 去掉小数点后面多余的0
查看>>
oracle - sqldeveloper 手动执行包 package的方法
查看>>
高并发、大流量网卡调优 _转
查看>>
如何写3DMAX的插件
查看>>
base64编码
查看>>
jquery.select2 模糊查询
查看>>
viewport
查看>>
【EMC】基本概念
查看>>
Visual Studio 2010 Express for Windows Phone Key!
查看>>
leetcode:Longest Substring Without Repeating Characters
查看>>
核心动画coreanimation总结(转)
查看>>
OAuth快速入门
查看>>
Python自动化运维之28、Django(二)
查看>>
带你理解JavaScript闭包
查看>>
Kubernetes — 作业副本与水平扩展
查看>>