SpringBoot整合EasyExcel模板导出Excel

创建SpringBoot项目

导入EasyExcel.jar

<dependency>
	<groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.1.6</version>
</dependency>

创建Excel模板

在这里插入图片描述

实体类

public class FillData {
	private String name;
	@NumberFormat("##.0")
	private Double chinese;
	@NumberFormat("##.0")
	private Double math;
	@NumberFormat("##.0")
	private Double english;
	@NumberFormat("##.0")
	private Double number;
	//getter setter
}

Service实现

@Service
public class ExcelExportServiceImpl implements ExcelExportService{
	//在springboot文件(application.properties)中配置模板所在的位置,例如
	//excel.template=E:/SpringToolSuiteForEclipseWorkSpace/PrivateApplication/EasyExcel/src/main/resources/1.xlsx
	@Value("${excel.template}")
	private String templateFileName;
	
	@Override
	public void excelExport(HttpServletResponse response) throws IOException {
		// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
		System.out.println(templateFileName);
		// 方案1 根据对象填充
		String fileName = "simpleFill" + System.currentTimeMillis() + ".xlsx";
		// 这里 会填充到第一个sheet, 然后文件流会自动关闭
		List<FillData> l = new ArrayList<>();
		for(Integer i = 0; i < 50; i++){
			FillData fillData = new FillData();
			fillData.setName("张三" + i+"号");
			fillData.setChinese(120.0+i);
			fillData.setEnglish(141.0+i);
			fillData.setMath(119.0+i);
			fillData.setNumber(fillData.getChinese()+fillData.getEnglish()+fillData.getMath());
			l.add(fillData);
		}
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-disposition","attachment;filename="+new String(fileName.getBytes(),"iso-8859-1"));
		EasyExcel.write(response.getOutputStream(),FillData.class).withTemplate(templateFileName).sheet().doFill(l);
	}
}

Service接口

public interface ExcelExportService {

	void excelExport(HttpServletResponse response) throws IOException;

}

控制器Controller

@RestController
public class HelloController {
	@Autowired
	private ExcelExportService excelExportService;
	
	@GetMapping("/h")
	public void h(HttpServletResponse response) throws IOException {
		excelExportService.excelExport(response);
	}
}

然后访问/h接口就可以导出一个

有问题的小伙伴欢迎留言评论,看了第一时间会回复的哈

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值