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

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

1.导入Maven依赖


        
			org.apache.poi
			poi
			3.17
		
 
		
			org.apache.poi
			poi-ooxml
			3.17
		
 
		
			com.alibaba
			easyexcel
			2.1.1
		

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 selectList = reserMapper.selectList(null);
		List 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();
		}
		
	}

你可能感兴趣的:(大数据)