一 操作案例
1.1 pom文件
<dependency>
<groupId>net.sf.jett</groupId>
<artifactId>jett-core</artifactId>
<version>0.11.0</version>
</dependency>
1.2 代码
/**
* @author liujianfu
* @description 导出 环保指标查询日,月,年数据
* @date 2022/12/1 16:39
* @param [response]
* @return void
*/
@RequestMapping("/export")
public void exportEnvCycleExcel(HttpServletResponse response) {
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("titleName","环保指标报表");
resultMap.put("reportDate", DateUtils.dateToStr(new Date(),"yyyy-MM-dd"));
//List<Student> studentsList=new ArrayList<>();
List<Map> studentsList=new ArrayList<>();
for(int k=0;k<5;k++){
Map<String,Object> map=new LinkedHashMap<>();
map.put("id",k);
map.put("name","李四"+k);
map.put("age",(k+1)*2);
studentsList.add(map);
}
resultMap.put("dataList",studentsList);
buildExcelReport( resultMap, response);
}
/**
* @author liujianfu
* @description 封装excel
* @date 2022/11/8 10:42
* @param [resultMap]
* @return void
*/
public void buildExcelReport(Map<String, Object> resultMap, HttpServletResponse response){
String modelFile="d:/model-test.xlsx";
try (InputStream is = new FileInputStream(new File(modelFile));) {
Workbook workbook = new ExcelTransformer().transform(is, resultMap);
buildExcelDocument("环保_"+System.currentTimeMillis()+".xlsx", workbook, response);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @author liujianfu
* @description 数据流的输出
* @date 2022/11/8 10:42
* @param [filename, workbook, response]
* @return void
*/
protected static void buildExcelDocument(String filename, Workbook workbook, HttpServletResponse response)
throws Exception {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
1.3 excel模板
<jt:forEach items="${dataList}" var="t"> ${t.id} ${t.name} ${t.age}</jt:forEach>
1.4 导出效果