SpringBoot整合EasyExcel实现表格导出操作

SpringBoot整合EasyExcel实现表格导出操作

1.导入Maven依赖


        <dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.17</version>
		</dependency>
 
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.17</version>
		</dependency>
 
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>easyexcel</artifactId>
			<version>2.1.1</version>
		</dependency>

2.创建一个与需要导入Excel文件头字段对应的实体类(index是字段所在列数)


@Data
public class ExcelData{
 
	@ExcelProperty(value="水库名",index=0)
	private String name;
	
	@ExcelProperty(value="水库分类名",index=1)
	private String categoryName;
	
	@ExcelProperty(value="面积",index=2)
	private Float area;
	
	@ExcelProperty(value="水库容积",index=3)
	private Float volume;
	
	@ExcelProperty(value="流域",index=4)
	private Float flows;
	
	@ExcelProperty(value="地理位置",index=5)
	private String location;
	
	@ExcelProperty(value="文件地址",index=6)
	private String file;
 

}

3.编写业务

	//================================业务导出==================
	@Override
	public void exportExcel(HttpServletResponse response) {
		List<Reser> selectList = reserMapper.selectList(null);
		List<ExcelData> exceldata = new ArrayList<>();
		selectList.stream().forEach(item -> {
			ExcelData newOne = new ExcelData();
			BeanUtils.copyProperties(item, newOne,"id");
			Category category = categoryMapper.selectById(item.getCategoryId());
			newOne.setCategoryName(category.getName());
			exceldata.add(newOne);
		});
		try {
			//设置响应格式
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
			String fileName =URLEncoder.encode("水库信息表","UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename="+fileName+".xlsx");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
            //核心   sheet是定义excel 下栏sheet的名称
			EasyExcel.write(response.getOutputStream(),ExcelData.class).sheet("模板").doWrite(exceldata);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值