Java在线数据导入导出Excel

利用hutool 导入导出 Excel

导入maven

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.20</version>
</dependency>

导入Excel

public ResponseData uploadExcel(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            reader.addHeaderAlias(“Excel标题名称”, “对应实体类别名”);
            List<Person> personList = reader.readAll(Person.class);
            personMapper.batchInsert(personList);
            return ResponseUtil.setData("success", "文件导入成功");
        } catch (Exception e) {
            log.error("文件导入失败 {}", e);
            return ResponseUtil.setErrorMsg("文件导入失败");
        }
    }

在线导出 xls 格式 Excel

导出Excel

@SneakyThrows
    @Override
    public void downloadExcel() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        List<Person> personList = personMapper.selectList();
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.addHeaderAlias(“实体类字段名”, “对应Excel标题名称”);
        writer.setOnlyAlias(true);
        writer.write(personList, true);
        // 设置字号
        Font font = writer.createFont();
        font.setFontHeightInPoints((short) 16);
        writer.getStyleSet().setFont(font, false);
        // 设置列宽
        writer.getSheet().setDefaultColumnWidth(24);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
         // 注意这里如果需要设置中文文件名,需要重新编码
        String filename = new String(“用户表_”.getBytes(), "iso8859-1") + LocalDate.now().format(formatter) + ".xls";
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }
posted @ 2022-03-28 15:58  暮雨寒冬  阅读(169)  评论(0编辑  收藏  举报