首页 > 代码库 > ExtAspNet从DataTable里导出Excel

ExtAspNet从DataTable里导出Excel

[csharp] view plaincopyprint?
  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.       }

 

 

ExtAspNet从DataTable里导出Excel