您的位置:首页 > 其它

Excel 导出

2009-06-26 10:00 127 查看
最近在做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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: