Java使用POI进行数据导出到Excel

数据导出为Excel在我们写项目的过程中经常用到

需要用到的jar包 poi-3.17.jar 官网下载地址 http://mvnrepository.com

具体实现步骤(在servlet中写)

	//第一步创建一个webbook,对应一个Excel文件
	HSSFWorkbook wb=new HSSFWorkbook();
	//第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
	HSSFSheet sheet=wb.createSheet("食物信息数据");
	//第三步,在sheet中添加表头第0行
	HSSFRow row = sheet.createRow(0);
	//第四步,创建单元格,并设置表头居中
	HSSFCellStyle style = wb.createCellStyle();
	style.setAlignment(HorizontalAlignment.CENTER);//居中格式
	HSSFCell cell = row.createCell(0);
	cell.setCellValue("编号");
	cell.setCellStyle(style);
	
	cell=row.createCell((short)1);
	cell.setCellValue("名称");
	cell.setCellStyle(style);
	
	cell=row.createCell((short)2);
	cell.setCellValue("类型");
	cell.setCellStyle(style);
	
	cell=row.createCell((short)3);
	cell.setCellValue("单价");
	cell.setCellStyle(style);
	
	cell=row.createCell((short)4);
	cell.setCellValue("库存");
	cell.setCellStyle(style);
	
	//第五步,写入实体数据,从数据库拿数据
	FoodController controller=new FoodController();
	List<Foods> foodsList = controller.foodsList(null, null);
	for (int i = 0; i < foodsList.size(); i++) {
		//创建单元格,并赋值
		row=sheet.createRow(i+1);
		Foods foods = foodsList.get(i);
		row.createCell((short)0).setCellValue(foods.getId());
		row.createCell((short)1).setCellValue(foods.getName());
		row.createCell((short)2).setCellValue(foods.getType());
		row.createCell((short)3).setCellValue(foods.getPrice());
		row.createCell((short)4).setCellValue(foods.getNum());
	}
	//第六步,下载Excel
	OutputStream out=null;
	out=response.getOutputStream();
	String fileName="食物信息.xls";
	response.setContentType("application/x-=msdownload");
	response.setHeader("Content-Disposition", "attachment; filename="
			+URLEncoder.encode(fileName, "UTF-8"));
	wb.write(out);

实现效果图

导出成功后数据成功显示
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忆晨丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值