asp.net学习笔记·将数据库中的数据保存在EXCEL文件中
提取数据库中的数据,将其保存在EXCEL文件中,并提供下载。
在一般处理程序中将数据库数据保存在EXCEL文件中的代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using NPOI.HSSF.UserModel; using good.DAl; using System.Data; namespace good { /// <summary> /// excel 的摘要说明 /// </summary> public class excel : IHttpHandler { Sql sql = new Sql(); IDataReader reader; public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/x-excel"; //设置类型 string filename = HttpUtility.UrlEncode("动态数据.xls"); context.Response.AddHeader("Content-Disposition","attachment;filename=" + filename); reader = sql.GetReader(); HSSFWorkbook workbook = new HSSFWorkbook();//新建EXCEL文件 HSSFSheet sheet = workbook.CreateSheet();//新建页 if (reader!= null ) { while (reader.Read()) { int i = 0; string userName = reader.GetString(reader.GetOrdinal("Name")); int id = (int)reader.GetValue(reader.GetOrdinal("ID")); HSSFRow row = sheet.CreateRow(i); //创建行 row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(userName);//创建cell并给Cell设置数据类型以及数据 row.CreateCell(1, HSSFCell.CELL_TYPE_NUMERIC).SetCellValue(id); } workbook.Write(context.Response.OutputStream);//将生成的EXCEL文件流输出到上下文中 } else { } //HSSFWorkbook workbook = new HSSFWorkbook(); //HSSFSheet sheet = workbook.CreateSheet(); //HSSFRow row1 = sheet.CreateRow(0); //HSSFCell cell1 = row1.CreateCell(0, HSSFCell.CELL_TYPE_STRING); //cell1.SetCellValue("你好"); } public bool IsReusable { get { return false; } } } }
操作数据库的代码
public IDataReader GetReader() { SqlConnection conn = new SqlConnection(strConn); try { conn.Open(); string strCmd = "select * from Person"; SqlCommand cmd = new SqlCommand(strCmd,conn); IDataReader reader = cmd.ExecuteReader(); return reader; } catch (Exception ex) { Console.WriteLine(ex.Message); return null; }
}