万事屋软件科技

C# dataGridView导出Excel源代码 C# dataGridView导出Excel源代码

1.实现的效果


2.所需dll文件

Excel.dll

百度一搜一大堆···

下载地址1http://ishare.iask.sina.com.cn/f/8234289.html

下载地址2http://api.dllzj.com/down/Excel.dll.html

 

3.添加以下引用

        添加的方法,是右键引用,选择添加引用(R))…,选择浏览如图图2,再选择Excel.dll文件,就可以添加了.

4.源代码

          #region 导出表格

            try

            {

                if (dataGridView1.RowCount == 0)

                {

                    return;

                }

                Excel.Application excel = new Excel.Application();

                excel.Application.Workbooks.Add(true);

                excel.Visible = true;

                for (int i = 0; i < dataGridView1.ColumnCount; i++)

                {

                    excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;

                }

                for (int i = 0; i < dataGridView1.RowCount - 1; i++)

                {

                    for (int j = 0; j < dataGridView1.ColumnCount; j++)

                    {

                        excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();

                        excel.Columns.AutoFit();//自动适应

                    }

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show("请检查是否安装Microsoft Office软件" + ex.Message);

            }

            #endregion