C# DataGridView导出excel的几种方法

第一种、首先本form上游datagridview的控件及数据,再建一个button控件作为导出按钮,在按钮click事件中写入以下代码

 //保存文件对话框
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel文件|*.xlsx|Word文件|*.docx";
            sfd.FilterIndex = 0;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string search = "select * from 旧备件表 where(0=0)";
                if (this.textBox1.Text.Length > 0)
                {
                    search = search + " and 物料编码=" + "" + textBox1.Text + "";
                }
                if (this.textBox2.Text.Length > 0)
                {
                    search = search + " and 设备号=" + "" + textBox2.Text + "";
                }
                if (this.textBox3.Text.Length > 0)
                {
                    search = search + " and 物料描述 like" + "‘%" + textBox3.Text + "%‘";//实现物料描述的模糊查询
                }
                if (this.textBox4.Text.Length > 0)
                {
                    search = search + " and 备件序列号 like" + "‘%" + textBox4.Text + "%‘";//实现备件序列号的模糊查询
                }
                //调用导出Excel的方法,传入DataTable数据表和路径
                SqlDataAdapter sda = new SqlDataAdapter(search, DataBase.GetSqlConnection());
                System.Data.DataTable dt = new System.Data.DataTable();
                //将数据库中查到的数据填充到DataTable数据表
                sda.Fill(dt);
                ExportExcel(dt, sfd.FileName);
            }
        }
        void ExportExcel(System.Data.DataTable dt, string filepath)
        {
            //创建Excel应用程序类的一个实例,相当于从电脑开始菜单打开Excel
            ApplicationClass xlsxapp = new ApplicationClass();
            //新建一张Excel工作簿
            Workbook wbook = xlsxapp.Workbooks.Add(true);
            //第一个sheet页
            Worksheet wsheet = (Worksheet)wbook.Worksheets.get_Item(1);
            //将DataTable的列名显示在Excel表第一行
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                //注意Excel表的行和列的索引都是从1开始的
                wsheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
            }
            //遍历DataTable,给Excel赋值
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    //从第二行第一列开始写入数据
                    wsheet.Cells[i + 2, j + 1] = dt.Rows[i][j];
                }
            }
            //保存文件
            wbook.SaveAs(filepath);
            //释放资源
            xlsxapp.Quit();
        }
    

第二种、大同小异

private void button3_Click(object sender, EventArgs e)
        {
            string fileName = "";
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xlsx";
            saveDialog.Filter = "Excel文件|*.xlsx";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
            //写入标题             
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            { worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; }
            //写入数值
            for (int r = 0; r < dataGridView1.Rows.Count; r++)
            {
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
            MessageBox.Show(fileName + "资料保存成功", "提示", MessageBoxButtons.OK);
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);  //fileSaved = true;                 
                }
                catch (Exception ex)
                {//fileSaved = false;                      
                    MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();//强行销毁           }
        }
    

3、正在研究前导零问题。。。待续

C# DataGridView导出excel的几种方法

上一篇:WPF中让TextBlock每一个字符显示不同的颜色


下一篇:Windows/Linux 制作ISO文件