一聚教程网:一个值得你收藏的教程网站

热门教程

asp.net HttpHandler从数据库表导出Excel文件

时间:2022-06-25 04:09:44 编辑:袖梨 来源:一聚教程网

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文件中加上:

   


    下载Excel
   

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

 

热门栏目