Excel 导出

     最近在做Excel导出的时用户突然提出需要对文件设置页眉和页脚,这个问题很是让人头痛.在网上查找资料的时候发现都做得很是复杂,最后自己对文件进行代码分析通过设置前后的不同发现可以用样式表进行处理,真个汗呀!下面代码贴出来分享一下.

 /// <summary>
        /// 传入的DataTable
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="xlsName"></param>
        public static void DataTableToExcel(DataTable dt, string xlsName)
        {
            xlsName = xlsName.Replace("查询", "");
            string style = @"<style> .text { mso-number-format:/@; }  ";
            string styleSetup = @"@page
         {mso-header-data:&C&/0022宋体/,加粗/0022&18&A;
         mso-footer-data:";
            styleSetup=styleSetup+'"'+" 第 &P 页,共 &N 页"+'"'+';';
            string other = @"margin:.98in .75in .98in .75in;
         mso-header-margin:.51in;
         mso-footer-margin:.51in;
         mso-page-orientation:landscape;}";
            style = style + styleSetup + other + "</style>";
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(xlsName, System.Text.Encoding.UTF8) + ".xls");
            HttpContext.Current.Response.Charset = "utf-7";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            GridView gv = new GridView();
            gv.Font.Size = 11;
            gv.DataSource = dt;
            gv.DataBind();
            gv.EnableViewState = false;
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            gv.RenderControl(hw);

            HttpContext.Current.Response.Write(style);
            HttpContext.Current.Response.Write(tw.ToString());

            HttpContext.Current.Response.End();
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值