@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, BaiyunProjectTalk baiyunProjectTalk) {
//获取模板
TemplateExportParams params = new TemplateExportParams("exportTempLate/projectTalk.xlsx");
Map<String, Object> map = new HashMap<>(); //需要导出的数据-所有
List<Map<String, Object>> listMap = new ArrayList<>(); //需要导出的数据-list
List<BaiyunProjectTalk> childrenlist = baiyunProjectTalkService.list();
childrenlist.forEach(item -> {
Map<String, Object> lm = new HashMap<>();// list数据
lm.put("projectId", item.getProjectId());
lm.put("content", item.getContent());
listMap.add(lm);
});
map.put("title", "项目沟通表");// 标题
map.put("maplist", listMap);// 需要循环的数据
// 模板导出
ModelAndView mv = new ModelAndView(new JeecgTemplateExcelView());
mv.addObject(TemplateExcelConstants.PARAMS, params);
mv.addObject(TemplateExcelConstants.MAP_DATA, map);
return mv;
}
POI导出Excel:
/**
* 让数据和表头一一对应
* @param headers key对应数据map的key value为表头的名称
*/
public static void export(HttpServletResponse response, String fileName, String sheetName, LinkedHashMap<String, String> headers, List<Map<String, Object>> exportList) {
ServletOutputStream outputStream = null;
try {
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName + ".xls", "UTF-8"));
outputStream = response.getOutputStream();
// 创建工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建表,并取名
HSSFSheet sheet = workbook.createSheet(sheetName);
// 设置表格默认宽度
sheet.setDefaultColumnWidth(20);
// 创建文本样式
HSSFCellStyle textCellStyle = workbook.createCellStyle();
DataFormat format = workbook.createDataFormat();
short textFormat = format.getFormat("@");// 文本格式
textCellStyle.setDataFormat(textFormat);
// 创建时间样式
HSSFCellStyle dateCellStyle = workbook.createCellStyle();
dateCellStyle.setDataFormat(format.getFormat("yyyy-MM-dd"));
// 记录表头行对应字段
List<String> headersText = new ArrayList<>();
// 设置表头行
HSSFRow headerRow = sheet.createRow(0);
int cellKey = 0;
for (Map.Entry<String, String> entry : headers.entrySet()) {
HSSFCell headerRowCell = headerRow.createCell(cellKey++);
headerRowCell.setCellStyle(textCellStyle);
headerRowCell.setCellValue(entry.getValue());
headersText.add(entry.getKey());
}
// 设置数据行
for (int i = 0; i < exportList.size(); i++) {
HSSFRow dataRow = sheet.createRow(i + 1);
Map<String, Object> map = exportList.get(i);
for (int j = 0; j < headersText.size(); j++) {
HSSFCell dataRowCell = dataRow.createCell(j);
String value = "";
if (map.containsKey(headersText.get(j))) {
value = (String) map.get(headersText.get(j));
}
dataRowCell.setCellValue(value);
dataRowCell.setCellStyle(textCellStyle);
}
}
// 导出Excel
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}