Java导出Excel工具--easyExcel
2019-05-18 本文已影响0人
JobanCai
Github:alibaba/easyexcel
以前用Apache的POI解析excel的工具,操作有点复杂,而且容易有OOM的风险。
调用web接口导出excel
maven 依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beta4</version>
</dependency>
code:
@GetMapping("/a")
public void cooperation(HttpServletRequest request, HttpServletResponse response)
throws IOException {
ServletOutputStream out = response.getOutputStream();
String fileName = new String((new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
.getBytes(), "UTF-8");
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
Sheet sheet = new Sheet(1, 0);
List<List<String>> head = new ArrayList<List<String>>();
List<String> headCoulumn1 = new ArrayList<String>();
List<String> headCoulumn2 = new ArrayList<String>();
headCoulumn1.add("第一列");
headCoulumn2.add("第二列");
head.add(headCoulumn1);
head.add(headCoulumn2);
Table table = new Table(1);
table.setHead(head);
sheet.setSheetName("下载数据");
writer.write0(getListString(), sheet, table);
writer.finish();
out.flush();
}
private List<List<String>> getListString() {
List<List<String>> result = new ArrayList<>();
for (int i = 0; i < 5; i++) {
List<String> item = new ArrayList<>();
item.add("testOne" + i);
item.add("testTwo" + i);
result.add(item);
}
return result;
}