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();
            }
        }   

时间: 2024-10-07 07:04:21

C#将DataTable数据导出到EXCEL的两种方法的相关文章

用easyui从servlet传递json数据到前端页面的两种方法

用easyui从servlet传递json数据到前端页面的两种方法 两种方法获取的数据在servlet层传递的方法相同,下面为Servlet中代码,以查询表中所有信息为例. //重写doGet方法 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stu

delphi 导出到excel的7种方法

本文来自 爱好者8888 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/kpc2000/article/details/17066823?utm_source=copy =================================================================================================== 第一种方法delphi 快速导出excel uses ComObj,clipbrd; funct

C# 将内存中的datatable数据导出为Excel(方法一,以文件流方式导出)【转载】

上次做了以Excel文件为数据源,进行数据导入,今天,给大家分享一下如何将内存中的datatable以文件流的方式导出为Excel文件,而且个人觉得这个方法非常不错,高效,简单. 技术要点:1.创建文件流,用于写最终的文件StreamWriter sw = new StreamWriter(fileName, false,Encoding.GetEncoding("gb2312")); 2.使用  StringBuilder类把数据组合为长字符串插入到excel文件中,sb.Appen

C# 将内存中的datatable数据导出为Excel(方法二,创建Excel对象导出)【转载】

上次写了一个用文件流方式将Datatable导出Excel的方法,这个方法有局限性,比如没法对Excel进行一些增加列颜色等简单的操作,现在,给大家介绍另外一种方法,用微软的Excel类.既然要用到类,那必须是你的机子要装上Excel才行呢. public  void DataTabletoExcel(System.Data.DataTable[] tmpDataTable,string date1,string date2) { string saveFileName = ""; S

利用HttpResponse将DataTable数据导出为Excel/Word/Txt/Html文档

Web项目中,很多时候须要实现将查询的数据集导出为Excel.Word等文档的功能,很多时候不太希望在工程中添加对Office组件相关的DLL的引用,甚至有时候受到Office不同版本的影响,导致在不同的服务器上部署后功能受限,或和其它项目冲突,那么,使用这种简单粗暴的方式,可能会解决部分猿类的烦恼忧愁. public static bool DataTableToExcel(System.Data.DataTable dataTable, string fileName) { if (data

Mysql查询结果导出为Excel的几种方法

具体原文找不到了,此篇是借鉴门户的一篇文章 方法一:查询语句直接输出语法格式: Example: select * into outfile '/data/var-3307/catid.xls' from help_cat where 1 order by cat_id desc limit 0,20; select * into outfile '导出文件存放目录' from 表面和查询条件等信息! 请注意权限问题,如果实在不行,放在/tmp 目录下 方法二:在shell命令行下把Excel以

将IList、DataTable数据导出到Excel

/// <summary> /// IList导出Excel /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list">集合</param> /// <param name="dataColumn">字段</param> /// <param name=&

C# 获取DataTable数据导出到Excel

1 protected void ExportExcel(System.Data.DataTable dt) 2 { 3 if (dt == null || dt.Rows.Count == 0) return; 4 Microsoft.Office.Interop.Excel.Application xlsxApp = new Application(); 5 if (xlsxApp == null) return; 6 //System.Globalization.CultureInfo C

c# 将Datatable数据导出到Excel表格中

public FileResult GetExcelFile()        {            if (Session["beginDate"] != null)            {                string bdate = Session["beginDate"].ToString();                DateTime ld = Convert.ToDateTime(Session["lastDate&q