• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c#listview导出excel文件

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

    }
}

 

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
VisualStudioC#中使用用户控件C#[ZT]发布时间:2022-07-13
下一篇:
在C#环境中动态调用IronPython脚本(二)发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap