下载excel模板

 

controller层:

@RequestMapping(value = "/template-download", method = RequestMethod.GET)
public ResponseEntity<byte[]> templateDownload() {
return xxService.templateDownload();
}

service层:
private static final String[] EXCEL_HEADER_NAMES = {"姓名", "年龄"};

public ResponseEntity<byte[]> templateDownload() throws RuntimeException {
logger.debug("进入了templateDownload方法");
try {
XSSFWorkbook wb = createExcelTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "download_template.xlsx");

//创建一个字节数组输出流对象
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wb.write(outputStream);

ResponseEntity<byte[]> returnFile = new ResponseEntity<byte[]>(outputStream.toByteArray(), headers, HttpStatus.OK);

outputStream.close();
return returnFile;
} catch (Exception ex) {
      logger.error(ex.getMessage());
      throw new RuntimeException(ex);
    }
}
/**
* 创建excel模版
*/
private XSSFWorkbook createExcelTemplate() {
List<String> headers = createHeaders();
if (CollectionUtils.isEmpty(headers)) {
throw new RuntimeException("下载模版失败");
}
XSSFWorkbook wb = new XSSFWorkbook();
ExcelUtils.createExcel(wb, headers);
return wb;
}

/**
* 创建header list
*
* @return
*/
private List<String> createHeaders() {
List<String> headers = new ArrayList<>();
for (String excelHeaderName : EXCEL_HEADER_NAMES) {
headers.add(excelHeaderName);
}
return headers;
}
ExcelUtils:
/**
* 创建excel
*/
public static void createExcel(XSSFWorkbook wb, List<String> headers) throws RuntimeException{
try {
XSSFSheet sheet = wb.createSheet();
//在sheet里创建第一行,这里即是表头
XSSFRow rowTitle = sheet.createRow(0);

//写入表头的每一个列
for (int i = 0; i < headers.size(); i++) {
//创建单元格
rowTitle.createCell(i).setCellValue(headers.get(i));
}
}catch (Exception e) {
logger.error(e.getMessage());

throw new RuntimeException(e);
}
}




posted on 2021-05-18 17:38  ssk&lzs  阅读(76)  评论(0编辑  收藏  举报

导航