使用httphandler实现 NPOI从数据库导数据进Office Exce
    ?
DownloadExcel 写道
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using System.Data.SqlClient;
using System.Data;
using Model;
namespace MYASP.httphandler
{
	/// <summary>
	/// DownloadExcel 的摘要说明
	/// http://www.cnblogs.com/gaoshuai/archive/2010/06/08/1753695.html
	/// </summary>
	public class DownloadExcel : IHttpHandler
	{
		public void ProcessRequest (HttpContext context)
		{
			int pageNum = 0; // 多少页
			int pageSize = 4;//每頁五萬條數據
			context.Request.ContentType = "application/x-excel";	//request
			context.Response.ContentType = "application/x-excel";	//Response
			string filename = HttpUtility.UrlEncode("下载数据.xls");//文件名进行url编码,防止乱码 
			context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
			HSSFWorkbook workbook =(HSSFWorkbook) new HSSFWorkbook();
			HSSFSheet sheet =null;
			//List<Log4j> list=new List<Log4j>();
			//list.Count();
			string  query="select * from log4j";
			using(SqlDataReader dr = SQLDBHelper.ExecuteReader(CommandType.Text, query, null))
			{
				int rownum = 0;
				int [] list= { rownum };
				while(dr.Read())
				{
					pageNum = (list.Count() % pageSize > 0) ? (list.Count() / pageSize + 1) : (list.Count() / pageSize);
					Console.WriteLine("sss"+pageNum);
					for(int i = 0 ; i < pageNum ; i++)
					{
						sheet = (HSSFSheet) workbook.CreateSheet("日志信息" + i);
						int count = (i + 1) * pageSize > list.Count() ? list.Count() : (i + 1) * pageSize;
						for(int j = i * pageSize ; j < count ; j++)
						{
							//list.Add(null);
							int id=(int) dr ["id"];
							string stamp=dr ["stamp"].ToString();
							string thread=dr ["infoLevel"].ToString();
							string clazz=dr ["clazz"].ToString();
							string message=dr ["message"].ToString();
							HSSFRow row =(HSSFRow) sheet.CreateRow(pageNum);  //创建第n行
							//把值填充到excle单元
							row.CreateCell(0).SetCellValue(id);
							row.CreateCell(1).SetCellValue(stamp);
							row.CreateCell(2).SetCellValue(thread);
							row.CreateCell(3).SetCellValue(clazz);
							row.CreateCell(4).SetCellValue(message);
						}
					}
					rownum++;
				}
			}
			workbook.Write(context.Response.OutputStream); //输入excle里面
		}
		/// <summary>
		/// 
		/// </summary>
		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
}
?数据脚本
?
?
?
?
--创建用户信息表
create database test;
create table log4j
(
id int identity(1,1) not null primary key,?
stamp varchar(10)not null, ? ?
thread varchar(30)not null, ? ? ?
clazz varchar(15)not null,
infoLevel varchar(15)not null,
message varchar(250)?
)