最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
asp.net HttpHandler从数据库表导出Excel文件
时间:2011-06-24 编辑:简简单单 来源:一聚教程网
asp教程.net HttpHandler从数据库教程表导出Excel文件
1.新建“导出Excel”asp.net教程 Web应用程序 文件。
2.拷贝NPOI库文件到新建的“lib”目录下,添加引用把7个.dll选上。
3.添加一般处理程序,文件名DownloadExcel1.ashx
4.建数据库UserDB.mdf 字段为:UserName,Password
5.在Default.aspx文件中加上:
6.在DownloadExcel1.ashx.cs文件中添加以下代码:
context.Response.ContentType = "application/x-excel";
string filename = HttpUtility.UrlEncode("用户数据.xls");
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet();
using (SqlConnection conn = new SqlConnection(@"Data Source=.SQLEXPRESS;AttachDBFilename=|DataDirectory|UserDB.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (IDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from T_Users";
using (IDataReader reader = cmd.ExecuteReader())
{
int rownum = 0;
while (reader.Read())
{
string username = reader.GetString(reader.GetOrdinal("UserName"));
string password = reader.GetString(reader.GetOrdinal("Password"));
HSSFRow row = sheet.CreateRow(rownum);
row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(username);
row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue(password);
rownum++;
}
}
}
}
workbook.Write(context.Response.OutputStream);
}
相关文章
- C#复制数组的两种方式及效率比较解读 10-24
- ASP.NET Identity用法解析 10-24
- ASP.NET MVC使用Identity增删改查用户介绍 10-24
- C语言中atoi函数模拟实现介绍 10-18
- .Net反向代理组件Yarp用法介绍 10-10
- .NET使用YARP通过编码方式配置域名转发实现反向代理教程 10-10