博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

.NET DataSet DataTable 导出excel

Posted on 2013-12-11 16:38  hyd309  阅读(615)  评论(0编辑  收藏  举报

public void CreateExcel(DataSet ds, string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName+".xls");
StringBuilder context = new StringBuilder("<table><thead><tr><th>序号</th><th>用户ID</th><th>部门</th><th>公司</th><th>最后登录日期</th></tr></thead><tbody>");
//逐行处理数据
int i = 0;
foreach (DataRow row in ds.Tables[0].Rows)
{
context.Append("<tr><td>" + ++i + "</td><td>");
context.Append(row["AccountId"].ToString() + "</td><td>");
context.Append(row["Department"].ToString() + "</td><td>");
context.Append(row["Company"].ToString() + "</td><td>");
context.Append(row["LastLogOnTime"] == null ? " " : row["LastLogOnTime"].ToString() + "</td></tr>");
}
context.Append("</tbody></table>");
resp.Write(context.ToString());
resp.End();
}