C# 将SQLSERVER的表导出为EXCEL

第一步,需要安装NuGet

1、点击项目中的管理 NuGet 程序包

2、搜索并安装 Microsoft.Office.Interop.Excel

 

第二步,创建EXCEL文件

1、说明:这一步主要是针对,导出为EXCEL文件时,没有对象文件所准备的,如果已经有明确导出的目标文件,第二步完全可以省略

2、程序:

        #region 创建EXCEL文件
        public void WriteExcel(string filename)
        {
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

            //判断指定路径中是否存在要创建的Excel
            Microsoft.Office.Interop.Excel.Workbook workBook;

            workBook = excelApp.Workbooks.Add(true);

            Microsoft.Office.Interop.Excel.Worksheet workSheet = workBook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;

            excelApp.Visible = false;
            excelApp.DisplayAlerts = false;

            workBook.SaveAs(filename);
            workBook.Close(false, Missing.Value, Missing.Value);

            excelApp.Quit();
            workSheet = null;
            workBook = null;
            excelApp = null;
            GC.Collect();
        }
        #endregion

第三步,导出到EXCEL表

1、这一步中加入了EXCEL对象文件的确认,也就是第二个if 的内容,这一部分没有在第二步中加入,是因为程序由此开始

2、如果程序有报错,请用 ALT + ENTER 补充 using 部分,一般是 System.IO、System.Reflection 之类的,看清楚加就行

3、程序:

        public string ExportExcel(DataSet ds, string saveFileName)
        {
            try
            {
                if (ds == null)
                    return "数据库为空";

                bool fileSaved = false;
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
                if (xlApp == null)
                {
                    return "无法创建Excel对象,可能您的机子未安装Excel";
                }
                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 < ds.Tables[0].Columns.Count; i++)
                {
                    worksheet.Cells[1, i + 1] = ds.Tables[0].Columns[i].ColumnName;
                }
                //写入数值
                for (int r = 0; r < ds.Tables[0].Rows.Count; r++)
                {
                    for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    {
                        worksheet.Cells[r + 2, i + 1] = ds.Tables[0].Rows[r][i];
                    }
                    System.Windows.Forms.Application.DoEvents();
                }
                worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
                if (saveFileName != "")
                {
                    try
                    {
                        workbook.Saved = true;

       // 判断该路径下是否有对应文件,没有则创建
                        if (File.Exists(saveFileName))
                        {
                            workbook.SaveCopyAs(saveFileName);
                        }
                        else
                        {
                            WriteExcel(saveFileName);
                            workbook.SaveCopyAs(saveFileName);
                        }
                        fileSaved = true;
                    }
                    catch (Exception ex)
                    {
                        fileSaved = false;
                        MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                    }
                }
                else
                {
                    fileSaved = false;
                }
                xlApp.Quit();
                GC.Collect();//强行销毁
                if (fileSaved && System.IO.File.Exists(saveFileName))
                {
                    //System.Diagnostics.Process.Start(saveFileName); //打开EXCEL
                    MessageBox.Show("文件保存成功");
                }
                return "成功保存到Excel";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

 

 

 

最后一步,调用数据库,选择所需的内容导出

1、连接数据库可能会用到 System.Data、System.Data.OleDb、System.Data.SqlClient 反正还是 ALT + ENTER

2、一定要确认数据库是不是本地,有没有密码

3、程序:

        //数据适配器
        SqlDataAdapter da = null;
        //数据集对象
        DataSet ds;
        // server= ;database= ;uid= ;pwd=  下面是连接本地数据库,所以不需要账号密码
        private string constr = "server = ;database = ; Trusted_Connection=true";

            SqlConnection con = new SqlConnection(constr);
            string sqlcom = "";int Switch_Case = 0;string SaveFilePath = "";

   // switch 方法里面 最好可以选一个变量,这样可以达到分类搜索数据库和保存的目的

   // 别的大佬应该有更好的方法,我水平有限,这里也建议写在 winform 中,这样可以手动填写或者选择数据库中的表
            switch ( )
            {
                case " ":
                    sqlcom = "这里写SQL语句"; Switch_Case = 1; break;
                case " ":
                    sqlcom = "这里写SQL语句"; Switch_Case = 2; break;
                case " ":
                    sqlcom = "这里写SQL语句"; Switch_Case = 3; break;

      // 还可以扩展更多,switch 就不多做介绍了 SQL语句一般也就是 SELECT * FROM XXX 这种
                default: break;
            }
            da = new SqlDataAdapter(sqlcom, con);
            ds = new DataSet();
            da.Fill(ds);

   // 这里就是对应上面选择的不同数据库中的表,创建导出的xls文件,路径注意格式,文件命名规范,最好也能与上面对应
            switch (Switch_Case)
            {
                case 1:
                    SaveFilePath = "D:\\case1" + DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss") + ".xls";
                    break;
                case 2:
                    SaveFilePath = "D:\\case2" + DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss") + ".xls";
                    break;
                case 3:
                    SaveFilePath = "D:\\case3" + DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss") + ".xls";
                    break;
                default: break;
            }

      // 调用上面从数据库导出的方法,输入两个设定好的内容即可
            ExportExcel(ds,SaveFilePath);

 

 

本文参考了以下两个网址,十分感谢:

https://blog.csdn.net/weixin_33912246/article/details/93563525

https://www.jb51.net/article/54318.htm

C# 将SQLSERVER的表导出为EXCEL

上一篇:EF MySql 连接错误


下一篇:解决oracle报: ora-12560: tns: 协议适配器错误