DataTable 导出到 Excel 类

底层类:

#region DataTable 导出到 Excel
        /// <summary>
        /// DataTable 导出到 Excel
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="captions">要导出的列标题</param>
        /// <param name="fieldNames">要导出的列名</param>
        /// <param name="sheetName">工作簿名称</param>
        /// <param name="isOpen">导出完成是否打开Excel,如果=false会杀死当前Excel进程</param>
        /// <returns>错误信息,如果为空,说明用户取消导入</returns>
        public static string DtToExcel(DataTable dt, string[] captions, string[] fieldNames, string sheetName, bool isOpen)
        {
            //返回的信息
            string str = "";
            //保存对话框
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "(*.xls,*.xlsx)|*.xls;*.xlsx";
            //保存的文件名称
            string fileName = "";
            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return "";
            }
            if (dt == null)
            {
                str = "表不能为空";
                return str;
            }
            if (captions.Length != fieldNames.Length)
            {
                str = "列名数目和列标题数目不匹配";
                return str;
            }
            foreach (string aa in fieldNames)
            {
                if (!dt.Columns.Contains(aa))
                {
                    str = "表中不存在列名为 " + aa + " 的列";
                    return str;
                }
            }
            //如果不是全部列都要导出,改变一下样式
            DataView dv = new DataView(dt);
            dt = dv.ToTable(false, fieldNames);

            //导出路径
            fileName = sfd.FileName;
            //定义Excel程序
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            //判断是否安装Excel
            if (excel == null)
            {
                str = "无法创建Excel对象,可能您的计算机未安装Excel!";
                return str;
            }
            //是否显示导出过程 ,建议关闭,否则在导出过程中鼠标点击Excel文件时会出错
            excel.Visible = false;
            //定义一个Excel文件
            Microsoft.Office.Interop.Excel.Workbook wBook = excel.Workbooks.Add(System.Reflection.Missing.Value);
            //定义工作表
            Microsoft.Office.Interop.Excel.Worksheet wSheet = (Microsoft.Office.Interop.Excel.Worksheet)wBook.Worksheets[1];
            Microsoft.Office.Interop.Excel.Range range;
            //获取行数、列数
            int rowCount = dt.Rows.Count;
            int colCount = captions.Length;

            //设置表格名称
            if (sheetName != null && sheetName.Length > 0)
            {
                wSheet.Name = sheetName;
            }
            else
            {
                wSheet.Name = dt.TableName;
            }

            if (rowCount < 1)
            {
                str = "没有记录可以导出";
                return str;
            }
            try
            {
                //写标题,标题居中
                for (int j = 1; j < captions.Length + 1; j++)
                {
                    excel.Cells[1, j] = captions[j - 1];
                }

                //设置对齐方式
                wSheet.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                //设置第一行高度,即标题栏
                ((Microsoft.Office.Interop.Excel.Range)wSheet.Rows["1:1", System.Type.Missing]).RowHeight = 20;
                //设置数据行行高度
                ((Microsoft.Office.Interop.Excel.Range)wSheet.Rows["2:" + dt.Rows.Count + 1, System.Type.Missing]).RowHeight = 16;
                //设置字体大小(10号字体)
                wSheet.Range[wSheet.Cells[1, 1], wSheet.Cells[dt.Rows.Count + 1, dt.Columns.Count]].Font.Size = 10;
                //设置单元格边框
                Microsoft.Office.Interop.Excel.Range range1 = wSheet.Range[wSheet.Cells[1, 1], wSheet.Cells[dt.Rows.Count + 1, dt.Columns.Count]];

                //往Excel写数据
                for (int m = 0; m < rowCount; m++)
                {
                    for (int n = 0; n < colCount; n++)
                    {
                        excel.Cells[m + 2, n + 1] = (object)dt.Rows[m][n] is DBNull ? "" : dt.Rows[m][n].ToString();
                    }
                }
                //保存工作表
                wSheet.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                wBook.Close(Type.Missing, Type.Missing, Type.Missing);

                ////设置EXLCE最大化
                //excel.WindowState = XlWindowState.xlMaximized;

                //提示信息
                str = "导出成功! 共导出 " + rowCount + " 条数据";
                return str;
            }
            catch (Exception ex)
            {
                str = "导出异常,请重试";
                return str;
            }
            finally
            {
                if (isOpen)
                {
                    //前台显示给用户
                    excel.Visible = true;
                    wSheet = null;
                    excel = null;
                }
                else
                {
                    excel.Visible = false;
                    excel.Quit();
                    // excel = null;
                    //杀死Excel 进程
                    KillProcess(excel);
                }

                GC.Collect();
            }

        }
        #endregion

调用(举例):

 string str=Functionjsj.DtToExcel(dt, new string[] { "学号", "姓名", "年龄" },
               new string[] { "Stu_Number", "Stu_Name", "Stu_Age" }, "学生信息",false);
           if (str.Length > 0) {
               MessageBox.Show(str, System.Windows.Forms.Application.ProductName);
               return;
           }
时间: 2024-10-13 21:56:48

DataTable 导出到 Excel 类的相关文章

DevExpress GridControl GridView 导出到 Excel 类

说明: 1>GridView 导出到 Excel (如果分页,只导出当前页数据) 2>GridView 导出到 Excel 3>方法2可以参考DataTable 导出到 Excel 自定义类如下: #region GridView 导出到 Excel Method First /// <summary> /// GridView 导出到 Excel (如果分页,只导出当前页数据) /// </summary> /// <param name="gv

DataTable导出到Excel

static DataTable GetTable() { // // Here we create a DataTable with four columns. // DataTable table = new DataTable(); table.Columns.Add("Dosage", typeof(int)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patien

把DataTable导出为Excel文件

今天项目里遇到了需要把DataTable导出为Excel的问题将解决方案记录在园子备忘 需要一些东西第三方的类库Aspose.Cells此处随意找个下载链接:http://www.cr173.com/soft/66096.html本人不保证该链接的合法性和有效性 说重点,上Demo public bool ExportAsExcel(string URI, DataSet ds) { Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();

DataTable导出到Excel文件

调用方法: ExcelHelper.Export(dtTemp, "供应商App", DlgSave.FileName, "物料文档" , new string[10] { "MatterCode", "MatterName", "MatterType", "MainUnit", "TagModelName", "LotName", "F

c# DataTable导出为excel

/// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <param name="dt">要导出的DataTable</param> public static void ExportToExcel(System.Data.DataTable dt) { if (dt == null) return; Microsoft.Office.Interop.Excel.Ap

C# datatable 导出到Excel

datatable导出到Excel /// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <param name="dt">要导出的DataTable</param> public static void ErrorCrd_ExportToExcel(DataTable dt) { if (dt == null) return; Microsoft.Office.I

将DataTable导出为Excel文件的方法

 需求:前台点击某个按钮,在后台从数据库中获取某DataTable数据到处成Excel文件. 1.Asp按钮控件 两个按钮,分别调用两种导出Excel文件的后台方法. <%--第一种方法--%> <form id="form1" runat="server"> <div> <asp:Button runat="server" OnClick="Btn1_Click" ID="

excel导出 按dataset里的datatable导出一个excel多个sheet 和 datatable导出

//datatable导出 public static void DataTableToExcel(string filename, string sheetName, DataTable table) { //增加序号列 //rui.dbHelper.insert序号(table, 0); IWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(sheetName); //设置单元格的样式:水平垂

DataTable导出为Excel

/// <summary> /// 导出Excel Datatable版本 /// </summary> /// <param name="dt">导出的Datatable</param> /// <param name="ExcelName">导出EXCEL的名称 不需要要带有扩展名_xls</param> public static void NewExportExcelScore(Data