ExtAspNet从DataTable里导出Excel

[csharp] view plain copy print ?
  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(""); 
  15.         sb.Append("
  16. "); 
  17.         foreach (DataColumn column in dt.Columns) 
  18.         { 
  19.             sb.AppendFormat("
  20. ", column.Caption); 
  21.         } 
  22.         sb.Append("
  23. "); 
  24.  
  25.         foreach (DataRow row in dt.Rows) 
  26.         { 
  27.             sb.Append("
  28. "); 
  29.             for (int i = 0; i < dt.Columns.Count;i++ ) 
  30.             { 
  31.                 string html = row[i].ToString(); 
  32.                 sb.AppendFormat("
  33. ", html); 
  34.             } 
  35.             sb.Append("
  36. "); 
  37.         } 
  38.         sb.Append("
  39. {0}
    {0}
    "
    ); 
  40.         return sb.ToString(); 
  41.       }

 

 

你可能感兴趣的:(ExtAspNet从DataTable里导出Excel)