天天看点

springboot内置下载模版

需求

1、springboot项目,在项目中放置一个模版EXCEL,然后通过连接下载下来

@Log("供应商-下载导入模板")
    @ApiOperation(value = "供应商-下载导入模板", response = String.class)
    @GetMapping(value = "/downloadSupplierTemplate")
    @AnonymousAccess
    public void supplierTemplate(HttpServletResponse response) throws Exception {
        supplierService.downloadSupplierTemplate(response);
    }      
/**
     * 供应商-下载导入模板
     *
     * @param response
     * @return
     */
    void downloadSupplierTemplate(HttpServletResponse response) throws Exception;      

  

    @Override
    public void downloadSupplierTemplate(HttpServletResponse response) throws Exception {
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yMMddHHmmss");
        LocalDateTime dataTime = LocalDateTime.now();
        //格式化,不能用Date类的实例作为参数
        String dateTimeStr = format.format(dataTime);
        System.out.println(dateTimeStr);
        String fileName = "催收供应商导入" + dateTimeStr + ".xlsx";
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String fileSuffix = "template/supplier/supplier_settlement.xlsx";
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileSuffix);
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        // 设置输出的格式
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        workbook.write(response.getOutputStream());
        workbook.close();
    }      

继续阅读