欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Asp.net中DataTable导出到Excel的方法介绍

程序员文章站 2024-03-01 18:18:58
复制代码 代码如下:#region  datatable导出到excel        //...

复制代码 代码如下:

#region  datatable导出到excel
        /// <summary>
        /// datatable导出到excel
        /// </summary>
        /// <param name="pdata">datatable</param>
        /// <param name="pfilename">导出文件名</param>
        /// <param name="pheader">导出标题以|分割</param>
        public static void datatableexcel(system.data.datatable pdata, string pfilename, string pheader)
        {
            system.web.ui.webcontrols.datagrid dgexport = null;
            // 当前对话
            system.web.httpcontext curcontext = system.web.httpcontext.current;
            // io用于导出并返回excel文件
            system.io.stringwriter strwriter = null;
            system.web.ui.htmltextwriter htmlwriter = null;
            if (pdata != null)
            {
                string useragent = curcontext.request.servervariables["http_user_agent"].tolower();
                if (useragent.indexof("firefox") == -1)//火狐浏览器
                    pfilename = httputility.urlencode(pfilename, system.text.encoding.utf8);

                curcontext.response.addheader("content-disposition", "attachment; filename=" + pfilename + ".xls");
                curcontext.response.contenttype = "application/vnd.ms-excel";
                strwriter = new system.io.stringwriter();
                htmlwriter = new system.web.ui.htmltextwriter(strwriter);

                // 为了解决dgdata中可能进行了分页的情况,需要重新定义一个无分页的datagrid
                dgexport = new system.web.ui.webcontrols.datagrid();
                dgexport.datasource = pdata.defaultview;
                dgexport.allowpaging = false;
                dgexport.showheader = false;//去掉标题
                dgexport.databind();

                string[] arrheader = pheader.split('|');
                string strheader = "<table border=\"1\" style=\"background-color:gray;font-weight:bold;\"><tr>";
                foreach (string j in arrheader)
                {
                    strheader += "<td>" + j.tostring() + "</td>";
                }
                strheader += "</tr></table>";
                // 返回客户端
                dgexport.rendercontrol(htmlwriter);
                string strmeta = "<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=utf-8\"/>";
                curcontext.response.write(strmeta + strheader + strwriter.tostring());
                curcontext.response.end();
            }
        }
        #endregion