using NPOI.HSSF.UserModel; using System.Data.SqlClient; using Model; using System.Collections.Generic; using BLL; using NPOI.SS.UserModel; namespace WebApp { /// <summary> ///@Author:梁继龙 ///@Date:2012/7/28 ///@Description:用NPOI处理Excel一页超过6635行的Bug进行分页 /// 官方:http://npoi.codeplex.com/下载npoi组件 /// </summary> public class ExcelPageHandler : IHttpHandler //一般处理文件Handler它类似servlet { public void ProcessRequest(HttpContext context) { int pageNum = 0; // 多少页 int pageSize = 50000;//每頁五萬條數據、切记这个值不能大于65536,超过这个值Excel就报异常.请你测试一下这个数值. 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); string SQL = "where 1=1"; List<Users> userList = new UsersBLL().ExcelPage(SQL); //计算出多少页 pageNum = (userList.Count() % pageSize > 0) ? (userList.Count() / pageSize + 1) : (userList.Count() / pageSize); HSSFWorkbook workbook = (HSSFWorkbook)new HSSFWorkbook(); //遍历每一页 for (int i = 0; i < pageNum; i++) { // String[] topText = { "ID", "姓名", "密码", "地址" }; HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("客户资料" + (i + 1) + "");//excel页 //用三转符计算出多条数据 int count = (i + 1) * pageSize > userList.Count() ? userList.Count() : (i + 1) * pageSize; //遍历头文信息 //遍历从数据库读取每一页有多条数据页 for (int z = 0, j = i * pageSize; j < count; j++, z++) { // for (int k = 0, y = 0; k < topText.Length; k++, y++) //{ HSSFRow row = (HSSFRow)sheet.CreateRow(z); //创建第z行,这个值必须从零开始索引. // row.CreateCell(y + 1).SetCellValue(topText[k].ToString()); //ID /** *在Java里面是E get(int index); 故 list.get(j); List是一个接口 *在C# 里面是 T this[int index] { get; set; } list[] this代表本类 List是一个类 */ Users user = userList[j]; //在java里面的jxl.jar里面的 Label(int c, int r, String cont) //c 列 r行 cont内容 row.CreateCell(0).SetCellValue(user.Id);//这里不能在CreateCell里面加上j或z row.CreateCell(1).SetCellValue(user.UserName); row.CreateCell(2).SetCellValue(user.Address); //} } } workbook.Write(context.Response.OutputStream); //输入excle里面 } public bool IsReusable { get { return false; } } } }
--创建用户信息表
======================================测试SQL脚
create database excel; --创建数据库
drop table userInfo; --删除表
create table userInfo
(
id int identity(1,1) not null primary key, --顾客编号,主键
username varchar(1000)not null, --开户名
telephone varchar(1445)not null, --联系电话格式xxxx-xxxxxxxx或手机号11位
address varchar(2550) --居住地址,可选输入
)
--CREATE PROCEDURE p_customer AS
Begin
Declare @n bigint
Declare @Sql nvarchar(225)
set @n=0
while @n<1000000--导入十万条相同的数据
begin
--本数据作为测试.电话号码就用中文,字节会大点,来测试excel到底能存储多少M,不够可以自己改表属性
Set @Sql='Insert into userInfo Values(''你好!Excel!'',''生成的单元格添加到工作表中生成的单元格添加到工作表中生成的单元格添加到工作表中生成的单元格添加到工作表中生成的单元格添加到工作表中生成的单元'',''生成的单元格添加到工作表中生成的单元格添加到工作表中生成的单元格添加到工作表中生成的单元格添加到工作表中生成的单元格添加到工作表中生成的单元'')'
Exec (@Sql)
set @n=@n+1
End
end
select count(*) from userinfo;