c# listview导出excel文件

首先在工程中需要添加对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);
               }

    }
}

 

 

posted @ 2013-06-20 19:23  爱生活,爱编程  阅读(896)  评论(0编辑  收藏  举报