模板为
生成结果为
请求
@RequestMapping("/outdata")
public void second(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> stringStringHashMap = new HashMap<>();
stringStringHashMap.put("h1", "h1");
List<Map<String, String>> arrayList = new ArrayList();
arrayList.add(stringStringHashMap);
exportNoAcceptResult(arrayList, request, response);
}
/**
* 将指定数据插入到模板文件中,并将文件发送给前端
* @param stockInfoList 数据列表
* @param request
* @param response
* @return
*/
public void exportNoAcceptResult(List<Map<String, String>> stockInfoList, HttpServletRequest request, HttpServletResponse response) {
//1.加载Excel模板文件(文件路径按自己的存放路径填写)
String fileName = "F:\\export_template.xlsx";
File file = new File(fileName);
// log.info("待导出的数据记录:【{}】", stockInfoList.size());
System.out.println(fileName);
XSSFSheet sheet = null;
try (InputStream inputStream = new FileInputStream(file);
XSSFWorkbook xwb = new XSSFWorkbook(inputStream)) {
sheet = xwb.getSheetAt(0);
assert sheet != null;
XSSFCellStyle cellStyle = xwb.createCellStyle();
//设置单元格边框
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
//设置居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
//设置数据域
// sheet.shiftRows(3, 3 + stockInfoList.size(), stockInfoList.size(), true, false);
//2.遍历数据,将数据插入到数据域中
for (short i = 0; i < stockInfoList.size(); i++) {
XSSFRow row = sheet.createRow(3 + i);
Map<String, String> stringObjectMap = stockInfoList.get(i);
// StockInfoResponse stockInfo = stockInfoList.get(i);
XSSFCell cell = row.createCell(0);
cell.setCellStyle(cellStyle);
cell.setCellValue(i + 1);
cell = row.createCell(1);
cell.setCellStyle(cellStyle);
cell.setCellValue(stringObjectMap.get("h1"));
}
//3.将Excel文件通过Response输出到前端
OutputStream outputStream = response.getOutputStream();
// 清空response
response.reset();
response.setContentType("application/msexcel");//设置生成的文件类型
response.setCharacterEncoding("UTF-8");//设置文件头编码方式和文件名
response.setHeader("Content-Disposition", "attachment; "
+ " filename=" + new String("XX统计信息.xlsx".getBytes("utf-8"), "ISO8859-1"));
String origin = request.getHeader("Origin");
response.addHeader("Access-Control-Allow-Origin", origin);
xwb.write(outputStream);
} catch (IOException e) {
// System.println("").error("下载Excel模板异常,异常信息为:【{}】", e.getMessage(), e);
}
}