• C#将DataTable数据导出到EXCEL的两种方法


    1、在非服务器控件的页面导出数据,需要借助一张temp空页面post回后台的数据。

    前台:window.location.href = "../Temp.aspx";

    后台: try{

        dtSource = Session["MyDataTable"] //假设数据在Session中    

        if (dtSource == null || dtSource.Rows.Count == 0)
                {
                    return;
                }
                DataGrid dg = new DataGrid();
                dg.DataSource = dtSource;
                dg.DataBind();

                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Charset = "UTF-8";//GB2312
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";//text/csv
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");

                System.IO.StringWriter oSW = new System.IO.StringWriter();
                HtmlTextWriter oHW = new HtmlTextWriter(oSW);
                dg.RenderControl(oHW);
                HttpContext.Current.Response.Write(oSW.ToString());
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.Close();

        }catch(e){

        log.Error(e);
                Response.Redirect("原页面.aspx");

        }

     2、通过引用 Microsoft.Office.Interop.Excel.dll 和 Microsoft.CSharp.dll,不推荐,服务器需要安装Office才行 

    /// <summary>
            /// 该方法需要引用Microsoft.Office.Interop.Excel.dll 和 Microsoft.CSharp.dll
            /// 将数据由DataTable导出到Excel
            /// </summary>
            /// <param name="dataTable"></param>
            /// <param name="fileName"></param>
            /// <param name="filePath"></param>
            private string exportDataTableToExcel(DataTable dataTable, string fileName, string filePath)
            {
                Microsoft.Office.Interop.Excel.Application excel;

                Microsoft.Office.Interop.Excel._Workbook workBook;

                Microsoft.Office.Interop.Excel._Worksheet workSheet;

                object misValue = System.Reflection.Missing.Value;

                excel = new Microsoft.Office.Interop.Excel.Application();

                workBook = excel.Workbooks.Add(misValue);

                workSheet = (Microsoft.Office.Interop.Excel._Worksheet)workBook.ActiveSheet;

                int rowIndex = 1;

                int colIndex = 0;

                //取得标题  
                foreach (DataColumn col in dataTable.Columns)
                {
                    colIndex++;

                    excel.Cells[1, colIndex] = col.ColumnName;
                }

                //取得表格中的数据  
                foreach (DataRow row in dataTable.Rows)
                {
                    rowIndex++;

                    colIndex = 0;

                    foreach (DataColumn col in dataTable.Columns)
                    {
                        colIndex++;

                        excel.Cells[rowIndex, colIndex] =

                             row[col.ColumnName].ToString().Trim();

                        //设置表格内容居中对齐  
                        //workSheet.get_Range(excel.Cells[rowIndex, colIndex],

                        //  excel.Cells[rowIndex, colIndex]).HorizontalAlignment =

                        //  Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
                    }
                }

                excel.Visible = true;

                string saveFile = filePath + fileName + ".xls";

                if (File.Exists(saveFile))
                {
                    File.Delete(saveFile);//嘿嘿,这样不好,偷偷把原来的删掉了,暂时这样写,项目中不可以
                }

                workBook.SaveAs(saveFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue,

                    misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,

                    misValue, misValue, misValue, misValue, misValue);

                dataTable = null;

                workBook.Close(true, misValue, misValue);

                excel.Quit();

                PublicMethod.Kill(excel);//调用kill当前excel进程  

                releaseObject(workSheet);

                releaseObject(workBook);

                releaseObject(excel);

                if (!File.Exists(saveFile))
                {
                    return null;
                }
                return saveFile;
            }
            /// <summary>
            /// 释放COM组件对象
            /// </summary>
            /// <param name="obj"></param>
            private static void releaseObject(object obj)
            {
                try
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                    obj = null;
                }
                catch
                {
                    obj = null;
                }
                finally
                {
                    GC.Collect();
                }
            }  
            /// <summary>
            /// 关闭进程的内部类
            /// </summary>
            public class PublicMethod
            {
                [DllImport("User32.dll", CharSet = CharSet.Auto)]

                public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);

                public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
                {
                    //如果外层没有try catch方法这个地方需要抛异常。
                    IntPtr t = new IntPtr(excel.Hwnd);

                    int k = 0;

                    GetWindowThreadProcessId(t, out k);

                    System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);

                    p.Kill();
                }
            }   

  • 相关阅读:
    Google 嘘! 嘘!
    zabbix fast
    zabbix
    kernel update
    列表推导
    Ddos 反射性防护 simple
    file cycle
    Scala
    Hadoop
    数据库
  • 原文地址:https://www.cnblogs.com/johnblogs/p/6001326.html
Copyright © 2020-2023  润新知