最近将自己在项目中经常用到的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();
}