将GridView数据导出为Excel

 

  private void btnDaochu_Click(object sender, EventArgs e)
        { 
            //导出Excel表

            Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
            if (dataGridView1.Rows.Count == 0)
            {
                return;
            }
           
            //实例化一个Excel.Applaction对象

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.DefaultExt = "xls";
            saveFileDialog.Filter = "Excel文件(*.xls)|*.xls";
            saveFileDialog.ShowDialog();

            string filepath = saveFileDialog.FileName;
            if (filepath.ToString().Length < 1)
            {
                return;
            }
            else
            {
                //让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写
                excel.Visible = false;

                //新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错
                //使用此方法在导出是不会占用进程
                Workbooks workbooks = excel.Workbooks;
                _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
              
                设置禁止弹出保存和覆盖的询问提示框  
                excel.DisplayAlerts = false;
                excel.AlertBeforeOverwriting = false;

                this.progressBar1.Visible = true;//设置进度条的可见性
                this.progressBar1.Minimum = 0;//最小值
                this.progressBar1.Maximum = dataGridView1.RowCount;//最大值

                //生成Excel中列头名称  
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
                }
                //把DataGridView当前页的数据保存在Excel中  
                for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                {
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
                    }
                  
                    this.progressBar1.Value += 1;
                    this.progressBar1.Refresh();
                }
                workbook.SaveCopyAs(filepath);
                workbook.Saved = true;
                excel.UserControl = false;
                excel.Quit();
                MessageBox.Show("导出成功!!");
            }

        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值