ExtAspNet从DataTable里导出Excel

  1. protected void btn_ToExcel_Click(object sender, EventArgs e) 
  2.     { 
  3.         Response.ClearContent(); 
  4.         Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); 
  5.         Response.ContentType = "application/excel"
  6.         Response.Write(GetDataTableHtml((DataTable)ViewState["tt"])); 
  7.         Response.End(); 
  8.     } 
  9.  
  10.  
  11. private string GetDataTableHtml(DataTable dt) 
  12.     { 
  13.         StringBuilder sb = new StringBuilder(); 
  14.         sb.Append("<table cellspacing=\"0\" rules=\"all\" border=\"1\" style=\"border-collapse:collapse;\">"); 
  15.         sb.Append("<tr>"); 
  16.         foreach (DataColumn column in dt.Columns) 
  17.         { 
  18.             sb.AppendFormat("<td>{0}</td>", column.Caption); 
  19.         } 
  20.         sb.Append("</tr>"); 
  21.  
  22.         foreach (DataRow row in dt.Rows) 
  23.         { 
  24.             sb.Append("<tr>"); 
  25.             for (int i = 0; i < dt.Columns.Count;i++ ) 
  26.             { 
  27.                 string html = row[i].ToString(); 
  28.                 sb.AppendFormat("<td>{0}</td>", html); 
  29.             } 
  30.             sb.Append("</tr>"); 
  31.         } 
  32.         sb.Append("</table>"); 
  33.         return sb.ToString(); 
  34.       }

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。