winform DataGridView 导出到Excel表格 分类: WinForm 2014-07-04 10:48 177人阅读 评论(0) 收藏

   public bool ExportDataGridview(DataGridView gridView)
        {
            if (gridView.Rows.Count == 0)
            {
                return false;
            }
            //创建Excel对象
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Application.Workbooks.Add(true);

            excel.Cells[1, 1] = gridView.Columns[3].HeaderText;
            excel.Cells[1, 2] = gridView.Columns[4].HeaderText;
            excel.Cells[1, 3] = gridView.Columns[5].HeaderText;
            excel.Cells[1, 4] = gridView.Columns[6].HeaderText;
            excel.Cells[1, 5] = gridView.Columns[7].HeaderText;
            //填充数据
            for (int i = 0; i < gridView.RowCount; i++)   //循环行
            {
                for (int j = 3; j < gridView.ColumnCount; j++) //循环列
                {
                    if (gridView[j, i].ValueType == typeof(string))
                    {
                        excel.Cells[i + 2, j - 2] = "'" + gridView.Rows[i].Cells[j].Value.ToString();
                    }
                    else
                    {
                        excel.Cells[i + 2, j - 2] = gridView.Rows[i].Cells[j].Value.ToString();
                    }
                }             
            }
            PublicClass.ShowMessage("共导出数据" + DgvCarriers.Rows.Count + "条!");
            //设置禁止弹出保存和覆盖的询问提示框  
            excel.Visible = true;
            GC.Collect();
            return true;
        }
        private void btnOut_Click(object sender, EventArgs e)
        {         
            ExportDataGridview(DgvCarriers);
        }
    }

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2014-07-04 10:48  Jackerson  阅读(91)  评论(0编辑  收藏  举报