ASP.NET 导出 excel 方法

1、获取数据源

IQueryable<Entity.User> mQuery = mDAL.GetUserList();

2、设置输出格式及文件编码格式

string mFileName = "×××××.xls";
Response.AppendHeader(
"Content-Disposition", "attachment;filename=" + Server.HtmlEncode(mFileName) + "");
Response.ContentEncoding
= System.Text.Encoding.UTF8;
Response.Write(
"<meta http-equiv=Content-Type content=application/ms-excel;charset=UTF-8>");

3、组装输出内容

       System.IO.StringWriter writer = new System.IO.StringWriter();
StringBuilder html
= new StringBuilder();
html.Append(
"<table cellspacing=\"1\" border=\"1\" CellPadding=\"1\">");
html.Append(
"<tr>");
html.Append(
"<td>");
html.Append(
"编号");
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(
"姓名");
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(
"电话号码");
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(
"性别");
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(
"邮箱地址");
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(
"居住地址");
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(
"出生年月");
html.Append(
"</tr>");

foreach (Entity.User item in mQuery)
{
html.Append(
"<tr>");
html.Append(
"<td>");
html.Append(item.ID);
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(item.Name);
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(item.Phone);
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(item.Sex
== 1 ? "" : "");
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(item.Email);
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(
item.Address);
html.Append(
"</b></td>");
html.Append(
"<td>");
html.Append(item.Birthday);
html.Append(
"</b></td>");
html.Append(
"</tr>");
}
html.Append(
"</table>");
Response.Write(html.ToString());
Response.End();

4、生成结果

posted @ 2011-05-19 13:37  darjuan  阅读(433)  评论(3编辑  收藏  举报