ExtAspNet从DataTable里导出Excel
来源:程序员人生 发布时间:2014-10-06 08:00:00 阅读次数:2618次
[csharp]
view plaincopyprint?
- protected
void btn_ToExcel_Click(object sender, EventArgs e)
- {
- Response.ClearContent();
- Response.AddHeader("content-disposition",
"attachment; filename=MyExcelFile.xls");
- Response.ContentType = "application/excel";
- Response.Write(GetDataTableHtml((DataTable)ViewState["tt"]));
- Response.End();
- }
-
-
- private string GetDataTableHtml(DataTable dt)
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">");
- sb.Append("<tr>");
- foreach (DataColumn column
in dt.Columns)
- {
- sb.AppendFormat("<td>{0}</td>", column.Caption);
- }
- sb.Append("</tr>");
-
- foreach (DataRow row
in dt.Rows)
- {
- sb.Append("<tr>");
- for (int i = 0; i < dt.Columns.Count;i++ )
- {
- string html = row[i].ToString();
- sb.AppendFormat("<td>{0}</td>", html);
- }
- sb.Append("</tr>");
- }
- sb.Append("</table>");
- return sb.ToString();
- }
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠