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

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.代码下载https://files.cnblogs.com/hao1234/%E5%AF%BC%E5%87%BAexcel.rar

posted on 2011-06-23 22:23  smxlcs  阅读(885)  评论(1)    收藏  举报