您的位置:首页 > 数据库

NPOI从数据库中导出到Excel

2012-02-24 11:04 190 查看
一,如何把数据库的数据导入到Excel?

(1)可以使用多种方式,但是较好的一种是使用NPOI。

(2)NPOI的缺陷:只能在Office2003中使用,Office2007无法使用NPOI,同时对于WPS也不能使用。

(3)使用是要引入NPOI的dll外部文件,下面的代码使用了简单三层的思想。

二,把数据库中的数据导入到Excel的具体步骤:

protected void Button2_Click(object sender, EventArgs e)

{

try

{

//使用NPOI创建Excel

HSSFWorkbook workbook = new HSSFWorkbook();

HSSFSheet sheet = workbook.CreateSheet();

HSSFRow row;
//使用三层得到所有的数据,数据量小时,可以这么做,当数据量很大时,要使用DataReader

UserInfoBLL userBll = new UserInfoBLL();

IEnumerable<UserInfo> list = userBll.GetAll();

//写入Excel的第一行,标题

row = sheet.CreateRow(0);

row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue("姓名");

row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue("年龄");

row.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue("邮箱");

row.CreateCell(3, HSSFCell.CELL_TYPE_STRING).SetCellValue("手机");

row.CreateCell(4, HSSFCell.CELL_TYPE_STRING).SetCellValue("时间");

row.CreateCell(5, HSSFCell.CELL_TYPE_STRING).SetCellValue("地址");

row.CreateCell(6, HSSFCell.CELL_TYPE_STRING).SetCellValue("备注");

//依次遍历结果集,并赋值

int i=1;

foreach(var userinfo in list)

{

row = sheet.CreateRow(i);

row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(userinfo.UserName);

row.CreateCell(1, HSSFCell.CELL_TYPE_NUMERIC).SetCellValue(Convert.ToInt32(userinfo.Age));

row.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue(userinfo.Email);

row.CreateCell(3, HSSFCell.CELL_TYPE_STRING).SetCellValue(userinfo.Telephone);

row.CreateCell(4, HSSFCell.CELL_TYPE_NUMERIC).SetCellValue(Convert.ToDateTime( userinfo.AddDate));

row.CreateCell(5, HSSFCell.CELL_TYPE_STRING).SetCellValue(userinfo.Address);

row.CreateCell(6, HSSFCell.CELL_TYPE_STRING).SetCellValue(userinfo.Remarks);

i++;

}

//操作文件流,写入到Excel中

using (Stream stream = new FileStream(@"G:\userInfoOut.xls", FileMode.OpenOrCreate, FileAccess.ReadWrite))

{

workbook.Write(stream);

}

Response.Write("导出成功");

}

catch (Exception ex)

{

Response.Write("错误:" + ex.Message);

}

}

三 ,参考
(1),此种做法只能针对数据量较小的数据,对于数据很多的导出,则不能使用这种方式。
(2),如何使用NPOI把Excel中的数据导入到数据库,请参考本博客相关文章。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: