一:原因
近几年项目中,一直会使用easyExcel ,1.封装性 2.性能较好,3.使用方便,所以目前在新需求中,一般会采用该方式。
二:使用
引入pom 文件:
<!-- easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
导出工具类:
public static void exportModule(String filename, HttpServletResponse response, Class<?> classModule, List<?> data) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8'zh_cn'"+ getFilename(filename));
EasyExcel.write(response.getOutputStream(), classModule).sheet("1").doWrite(data);
}
private static String getFilename(String filename) throws UnsupportedEncodingException {
String fileName = filename+ DateUtils.formatDate(new Date());
return URLEncoder.encode(fileName,"UTF-8") +".xlsx";
}
导出实体vo定义:
public class OrderExportVo implements Serializable {
@ExcelProperty(value = "卖家姓名",index = 0)
private String sellerName;
public String getSellerName() {
return sellerName;
}
public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}
controller 调用:
@RequestMapping("/export")
public PoppyResponse<?> export(HttpServletResponse response,
@RequestParam(required = false, value = "startDate") String startDate,
@RequestParam(required = false, value = "endDate") String endDate) {
try {
List<Vo> exportUsers = new ArrayList<>();
QueryVo query = new QueryVo();
int page = 1;
int pageSize = 100;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
if (startDate != null) {
Long start = dateFormat.parse(startDate).getTime();
query.setStartTime(start);
}
if (endDate != null) {
Long end = dateFormat.parse(endDate).getTime();
query.setEndTime(end);
}
query.setPageSize(pageSize);
query.setOrderStatus(status);
logger.info("query:{}", JSON.toJSONString(query));
while (true) {
query.setCurPage(page++);
Page<Vo> list = xxxService.query(query);
if (CollectionUtils.isEmpty(list.getContents())) {
break;
}
exportUsers.addAll(list.getContents());
if (page > 100000) {
break;
}
}
ExcelUtils.exportModule("export_info_", response, OrderExportVo.class, exportUsers);
} catch (Exception e) {
logger.error("export error ", e);
}
return PoppyResponse.success("export success");
}
三:总结
要善于总结,善于积累,未来加油!
|