首页 > 学院 > 开发设计 > 正文

asp.net webform/mvc导出Excel通用代码

2019-11-17 02:02:33
字体:
来源:转载
供稿:网友

asp.net webform/mvc导出Excel通用代码

Posted on 2015-03-20 14:31 haishu 阅读(...) 评论(...) 编辑 收藏

最近将自己在项目中经常用到的excel导出方法分析如下,如有不妥之处望他人指出,如果有更好的方法希望展示出来互相学习。

//导出事件

PRotected void btnexcel_Click(object sender, EventArgs e)

{

//定义导出Excel的标题

  List<string> tabletitle = new List<string>();   tabletitle.Add("企业注册号");   tabletitle.Add("企业名称");   tabletitle.Add("企业开业日期");

  DataTable dt=GetCompanyList();

Print(dt, tabletitle);

}

/// <summary> /// 输出Excel /// </summary> /// <param name="dt">数据</param> /// <param name="title">表头</param> public static void Print(DataTable dt, List<String> title) { StringBuilder sHtml = new StringBuilder(); sHtml.Append("<meta http-equiv='content-type' content='application/ms-excel; charset=UTF-8'/>"); sHtml.Append("<table border=1>"); sHtml.Append("<tr style='background-color:#D8DFF1;'>"); foreach (String s in title) { sHtml.Append("<td>"); sHtml.Append(s); sHtml.Append("</td>"); } sHtml.Append("</tr>"); foreach (DataRow row in dt.Rows) { sHtml.Append("<td style=/"vnd.ms-excel.numberformat:@/">"); //注:style=/"vnd.ms-excel.numberformat:@/" 去除科学计数法表示方式,以文本方式显示。 sHtml.Append(row["zch"].ToString()); sHtml.Append("</td>"); sHtml.Append("<td>"); sHtml.Append(row["qymc"].ToString()); sHtml.Append("</td>"); sHtml.Append("<td>"); sHtml.Append(row["kyrq"] != null && row["kyrq"].ToString() != "" ? Convert.ToDateTime(row["kyrq"]).ToString("yyyy-MM-dd") : ""); sHtml.Append("</td>"); sHtml.Append("</tr>"); } sHtml.Append("</table>");

System.Web.HttpContext.Current.Response.Charset = "GB2312"; System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode( DateTime.Now.ToString("yyyyMMddhhmmsss") + ".xls", System.Text.Encoding.UTF8).ToString()); System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel"; System.Web.HttpContext.Current.Response.Output.Write(sHtml); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End();

}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表