SpringBoot project EasyExcel use

SpringBoot project EasyExcel use


foreword

EasyExcel is a Java-based, fast, concise Excel processing tool that solves the memory overflow of large files.
It allows you to quickly complete functions such as reading and writing Excel without considering factors such as performance and memory.

1. EasyExcel export data to disk

1. Dependency added

EasyExcel needs to depend on

 <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.1.0</version>
</dependency>

2. Write the file to the local

Write data to excel and store locally

 public void dowloadDataExcel() {
    
    
        try {
    
    
            String fileName = "导出测试";
            //表头
            List<List<String>> heads = Lists.newArrayList();
            heads.add(Lists.newArrayList("姓名"));
            heads.add(Lists.newArrayList("英文名称"));
            heads.add(Lists.newArrayList("密码"));
            heads.add(Lists.newArrayList("角色"));
            heads.add(Lists.newArrayList("手机号"));
			// 数据
            List<List<String>> contents = Lists.newArrayList();
            for (int i = 0; i <= 10; i++) {
    
    
                List<String> content = Lists.newArrayList();
                for (int j = 0; j < 5; j++) {
    
    
                    content.add("第" + i + "行第" + j + "例内容");
                }
                contents.add(content);
            }

            EasyExcel.write("D:\\data\\test.xlsx")
            	.head(heads)
                .registerWriteHandler(new SimpleColumnWidthStyleStrategy(16)) // 列宽
                .sheet("数据").doWrite(contents);
        } catch (Exception e) {
    
    
            log.error("导出数据异常:{}", e.getMessage());
        }
    }

The resulting output is as follows
insert image description here

2. EasyExcel exports custom templates through the interface

1. Assemble the template and download it through the interface

Write the table header into excel and download it through the browser (note: after the nginx proxy, the file stream may be tampered with, causing the file to be damaged and cannot be opened)

   @GetMapping("/export/excel")
    @Timed
    @ResponseStatus(HttpStatus.OK)
    public void dowloadExcel(HttpServletResponse response) {
    
    
        try {
    
    
            // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("用户模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            List<List<String>> heads = Lists.newArrayList();
            heads.add(Lists.newArrayList("姓名"));
            heads.add(Lists.newArrayList("英文名称*"));
            heads.add(Lists.newArrayList("密码*"));
            heads.add(Lists.newArrayList("角色"));
            heads.add(Lists.newArrayList("手机号"));

            EasyExcel.write(response.getOutputStream())
                .head(heads)
                .registerWriteHandler(new SimpleColumnWidthStyleStrategy(16))
                .sheet("用户数据")
                .doWrite(null);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            log.error("导出模板异常:{}", e.getMessage());
        }
    }

The resulting output is as follows
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-tfatQEDm-1676599385893)(https://img-blog.csdnimg.cn/b405186638204d2b962abcb650410b88.png)]

3. EasyExcel adds excel default drop-down data

1.Excel column setting drop-down data

We set the role column to the default drop-down data
1, custom processing class

public class CustomSheetWriteHandler implements SheetWriteHandler {
    
    



    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    
    

    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    
    
        //定义一个map key是需要添加下拉框的列的index value是下拉框数据
        Map<Integer, String[]> mapDropDown = new HashMap<>(3);
        //设置单位身份 值写死
        String[] role = {
    
    "系统管理员","平台管理员","数据工程师","配置管理员"};
        //下拉选在Excel中对应的第4列
        mapDropDown.put(3,role);

        //获取工作簿
        Sheet sheet = writeSheetHolder.getSheet();
        ///开始设置下拉框
        DataValidationHelper helper = sheet.getDataValidationHelper();
        //设置下拉框
        for (Map.Entry<Integer, String[]> entry : mapDropDown.entrySet()) {
    
    
            /*起始行、终止行、起始列、终止列  起始行为1即表示表头不设置**/
            CellRangeAddressList addressList = new CellRangeAddressList(1, 65535, entry.getKey(), entry.getKey());
            /*设置下拉框数据**/
            DataValidationConstraint constraint = helper.createExplicitListConstraint(entry.getValue());
            DataValidation dataValidation = helper.createValidation(constraint, addressList);
            sheet.addValidationData(dataValidation);
        }
    }
}

Use when generating excel

   public void dowloadExcel(HttpServletResponse response) {
    
    
        try {
    
    
            // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("用户模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            List<List<String>> heads = Lists.newArrayList();
            heads.add(Lists.newArrayList("姓名"));
            heads.add(Lists.newArrayList("英文名称*"));
            heads.add(Lists.newArrayList("密码*"));
            heads.add(Lists.newArrayList("角色"));
            heads.add(Lists.newArrayList("手机号"));

            EasyExcel.write(response.getOutputStream())
                .head(heads)
                .sheet("用户数据")
                .registerWriteHandler(new SimpleColumnWidthStyleStrategy(16))
                .registerWriteHandler(new CustomSheetWriteHandler())
                .doWrite(null);

        } catch (Exception e) {
    
    
            e.printStackTrace();
            log.error("导出模板异常:{}", e.getMessage());
        }
    }

The resulting output is as follows
insert image description here

4. EasyExcel reads excel data

1. Parse excel to read data

Read the excel data, here is to read each row and column, and then convert the object you want to process, EasyExcel also provides a method to directly map the data to the entity, you can learn by yourself

  public List<User> excelHandle(MultipartFile multipartFile) {
    
    
        List<User> list = new ArrayList<>();
        byte[] bytes;
        try {
    
    
            bytes = multipartFile.getBytes();
        } catch (IOException e) {
    
    
            log.error("excel解析异常:{}", e.getMessage());
            throw new BadRequestAlertException(ErrorCodes.INNER_ERROR, "excel解析异常");
        }
        try {
    
    
            InputStream inputStream = new ByteArrayInputStream(bytes);
            List<Map<Integer, String>> maps = ExcelUtils.readExcel(inputStream);
            for (int i = 0; i < maps.size(); i++) {
    
    
                Map<Integer, String> bookMaps = maps.get(i);
                User user = pauseUserDto(bookMaps);
                list.add(user);
            }
        } catch (Exception e) {
    
    
            log.error("上传表格数据异常:{}", e.getMessage());
            throw new BadRequestAlertException(ErrorCodes.INNER_ERROR, "上传表格数据异常,检查后重试");
        }
        return list;
    }

Summarize

The above is the SpringBoot integration of EasyExcel. The two easiest ways to use are import and export. Excel can also implement many other functions, such as reading excel data, and Object binding operations, etc., which will be introduced in turn later.

Guess you like

Origin blog.csdn.net/Oaklkm/article/details/129078606