创建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
接口就可以导出一个
有问题的小伙伴欢迎留言评论,看了第一时间会回复的哈