• 下载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);
    }
    }




  • 相关阅读:
    基本数据类型相互转换及操作方法
    python以及计算机原理基础简要摘录
    Linux程序包管理
    rpm命令详解
    Linux程序包管理
    Linux任务计划
    压缩,解压缩工具及bash脚本编程
    btrfs文件系统管理与应用
    LVM应用
    CSS核心技术
  • 原文地址:https://www.cnblogs.com/ssk913/p/14781966.html
Copyright © 2020-2023  润新知