zoukankan      html  css  js  c++  java
  • 下载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);
    }
    }




  • 相关阅读:
    Redis安装部署
    传输方式Topic和Queue的对比
    Hudson配置及使用
    linux 绿色版 bes 6.6服务安装
    LINUX磁盘管理
    并发用户数与 TPS 之间的关系
    性能测试场景
    计算并发用户数的五种方法
    让selenium自动化脚本运行的更快的技巧
    Jmeter学习
  • 原文地址:https://www.cnblogs.com/ssk913/p/14781966.html
Copyright © 2011-2022 走看看