1. pom dependency import
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
2. Template settings
1. Create an excel directory in the project
2. Configuration template (dataList, dataList2 are the exported data collections respectively, and the names must be consistent; fe means loop insertion, t is the collection element object, '{ {' starts, '}}' ends)
sheet1
sheet2 3. Code implementation
1. Set the entity DataEntity (Data2Entity is similar)
@Data
public class DataEntity implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String data1;
private String data2;
private String data3;
private String data4;
private String data5;
private String data6;
private String data7;
private String data8;
private String data9;
private String data10;
private String data11;
private String data12;
private String data13;
}
2. Get dataList (similar to dataList2)
public List<DataEntity> getDataList(Map<String, Object> param) {
return testDataServiceImpl.getDataList(param);
}
3. Export
public void exportDataExcel(Map<String, Object> param, HttpServletRequest request, HttpServletResponse response) {
try {
String fileName = "test";
String fileUrl = System.getProperty("user.dir") + "/excel/test.xlsx";
TemplateExportParams params = new TemplateExportParams(fileUrl, true);
params.setStyle(ExcelStyleType.BORDER.getClazz());
params.setSheetNum(5);
Map<String, Object> map = new HashMap<String, Object>();
map.put("dataList", getDataList(param));
map.put("dataList2", getData2List(param));
Workbook book = ExcelExportUtil.exportExcel(params, map);
// 下载方法
export(response, book, fileName);
} catch (Exception e) {
throw new RuntimeException("导出异常");
}
}
public void export(HttpServletResponse response, Workbook workbook, String fileName) throws Exception {
try {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
OutputStream output = response.getOutputStream();
workbook.write(output);
output.flush();
workbook.close();
output.close();
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}