项目场景:java最实用的excel导出(实用)
/** 通用excel导出接口
* fileName 导出的excel名称
* allList 导出数据list
* map 导出的列名 key:数据字段 value:字段名称
* */
public static <E> void allExcelResponse(HttpServletResponse response, String fileName, List<E> allList, Map<String,String> map){
if(CollectionUtil.isEmpty(allList)){
return;
}
cn.hutool.poi.excel.ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter();
try {
Set<String> strings = map.keySet();
for (String key : strings) {
writer.addHeaderAlias(key,map.get(key));
}
writer.setOnlyAlias(true);
writer.write(allList, true);
Font font = writer.createFont();
font.setFontHeight((short) 230);
writer.getStyleSet().setFont(font, false);
int columnCount = writer.getColumnCount();
for (int i = 0; i < columnCount; ++i) {
double width = SheetUtil.getColumnWidth(writer.getSheet(), i, false);
if (width != -1.0D) {
width *= 256.0D;
//此处可以适当调整,调整列空白处宽度
width += 420D;
writer.setColumnWidth(i, Math.toIntExact(Math.round(width / 256D)));
writer.setRowHeight(i, 15);
if (i == (columnCount - 1)) {
writer.setColumnWidth(i, 19);
}
}
}
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
writer.close();
IoUtil.close(out);
} catch (IOException e) {
e.printStackTrace();
} finally {
writer.close();
}
}
提示:希望能帮到小伙伴们~