datatable导出excel
/// <summary>
/// 导出excel
/// </summary>
/// <param name="dt">datatable</param>
/// <param name="FileName">excel名称</param>
/// <param name="page">this.Page</param>
public void ToExcel(DataTable dt, string FileName,System.Web.UI.Page page)
{
try
{
StringBuilder sb = new StringBuilder();
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
sb.Append("<table cellpadding='0' cellspacing='0' ><tr>");
for (int j = 0; j < dt.Columns.Count; j++)
{
sb.Append("<td style='background-color:gray;border:1px #D0D7E5 solid'>" + dt.Columns[j].ColumnName + "</td>");
}
sb.Append("</tr>");
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append("<tr>");
for (int q = 0; q < dt.Columns.Count; q++)
{
sb.Append("<td style='border:1px #D0D7E5 solid'>" + dt.Rows[i][q] + "</td>");
}
sb.Append("</tr>");
}
sb.Append("</table>");
page.Response.Write(sb.ToString());
page.Response.End();
}
catch (Exception ex) {
// page.Response.Write("导出失败," + ex.Message);
}
}
posted on 2012-03-01 16:49 JQuery-Ch 阅读(2164) 评论(0) 编辑 收藏 举报