您的位置:首页 > 理论基础 > 计算机网络

HttpHandler实现从数据库表导出Excel文件(使用NPOI库)

2011-06-23 22:23 561 查看
1.新建“导出Excel”asp.net Web应用程序 文件。

2.拷贝NPOI库文件到新建的“lib”目录下,添加引用把7个.dll选上。

3.添加一般处理程序,文件名DownloadExcel1.ashx

4.建数据库UserDB.mdf 字段为:UserName,Password

5.在Default.aspx文件中加上:

<div>
<a href ="DownloadExcel1.ashx">下载Excel</a>
</div>

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);
}

7.运行结果



的打开后文件:



http://down.51cto.com/ 下载NPOI包

8.代码下载http://files.cnblogs.com/hao1234/%E5%AF%BC%E5%87%BAexcel.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: