controller
@GetMapping("/export")
public void export(HttpServletResponse response, Entity entity) {
ExcelWriter writer = ExcelUtil.getWriter(true);
//水平左对齐,垂直中间对齐
writer.getStyleSet().setAlign(HorizontalAlignment.LEFT, VerticalAlignment.CENTER);
ServletOutputStream out = null;
try {
entityService.export(writer, entity);
//自定义标题别名
//设置响应头
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now()) + "-数据" + ".xlsx"
//设置响应头
, "utf-8"));
out = response.getOutputStream();
writer.flush(out, true);
} catch (Exception e) {
log.error("export error: ", e);
} finally {
// 关闭writer,释放内存
writer.close();
IoUtil.close(out);
}
}
service
void export(ExcelWriter writer, Entity entity);
serviceImpl
@Override
public void export(ExcelWriter writer, Entity entity) {
List<Map<String, Object>> exportData = new ArrayList<>();
List<Entity> formDataList = entitymapper.findAll(entity);//获取数据
for (int i=0;i<formDataList.size();i++){
Map<String, Object> dataDetail = new LinkedHashMap<>(formDataList.size() + 2);
dataDetail.put("序号", i+1);
dataDetail.put("姓名",formDataList.get(i).getName());
dataDetail.put("联系电话",formDataList.get(i).getMobile());
dataDetail.put("身份证号",formDataList.get(i).getIdnumber());
dataDetail.put("内容",formDataList.get(i).getContent());
dataDetail.put("创建时间",formDataList.get(i).getCreatetime());
exportData.add(dataDetail);
}
writer.setColumnWidth(2, 30);
writer.setColumnWidth(3, 30);
writer.setColumnWidth(4, 100);
writer.setColumnWidth(5, 30);
writer.write(exportData);
}