Very simple Ali EasyExcel file import and export

Alibaba easyExcel depends on:

<!--阿里巴巴easyExcel-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.3.2</version>
</dependency>

First we do the file import:

  1. We create a simple excel file:

 2. We create an object UserDto
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDto {


    @ExcelProperty(value = "编号")
    private Long id;


    @ExcelProperty(value = "姓名")
    private String username;


    @ExcelProperty(value = "密码")
    private String password;

    @ExcelProperty(value = "手机号码")
    private String phone;
}
3. We create a listener
/**
 * 这是自定义的监听器
 */
@Component
public class ExcelListen implements ReadListener<UserDto> {

    private ArrayList<UserDto> oldList = new ArrayList<>();

    private ArrayList<UserDto> newList = new ArrayList<>();


    /**
     * 每读一行触发一次
     * @param userDto
     * @param analysisContext
     */
    @Override
    public void invoke(UserDto userDto, AnalysisContext analysisContext) {
        // 每读一行就给集合里面插入一次
        oldList.add(userDto);
    }

    /**
     * 全部读完以后触发一次
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        newList.clear();
        newList.addAll(oldList);
        oldList.clear();
    }

    /**
     * 将读取到的list返回
     * @return
     */
    public ArrayList getList(){
        return newList;
    }
}

In the listener, we implemented Ali’s ReadListener interface and implemented two methods. One is triggered once for each line read, and the second is triggered once after reading. We can write according to business needs. I am just doing a simple example here, writing the read content into a method and returning it.

4. The next step is our official interface, import file interface writing
    /**
     * 文件导入
     * @param file
     * @return
     */
    @PostMapping("/excelAdd")
    public ResponseResult lead(@RequestPart MultipartFile file) throws IOException {
        // 拿到文件输入流
        InputStream inputStream = file.getInputStream();
        // 在这里我们要创建一个监听器
        EasyExcel.read(inputStream, UserDto.class,excelListen)
                // 读第一张工作表,是从0开始
                .sheet(0)
                // 列头占一行
                .headRowNumber(1)
                .doRead();
        ArrayList list = excelListen.getList();
        System.out.println(list);

        return new ResponseResult(200,"导入成功");
    }

 I have annotated the function of the specific code, so that everyone can understand

5. Finally, we test to see if the printing result is what we need

  The result is correct

Next we demonstrate file export

1. We write the interface directly
    @GetMapping("/export")
    public ResponseResult export(HttpServletResponse response) throws IOException {
        // 自己先模拟一个数据集合,里面放我们的UserDto
        ArrayList<UserDto> userDtos = new ArrayList<>(Arrays.asList(new UserDto(1L,"cxx","123","321")));
        // 告诉前端我们返回的是个excel表
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        // 文件的名字
        String fileName = URLEncoder.encode("测试数据", "utf-8").replaceAll("\\+", "%20");
        // 响应头
        response.setHeader("Content-disposition","attachment;fileName" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream())
                // 设置表头,我们UserDto打了 @ExcelProperty注解的字段
                .head(UserDto.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("测试数据")
                .doWrite(userDtos);
        return new ResponseResult(200,"导出成功");

    }

  I have commented the function of each line of code, so that everyone can understand

2. We directly look at the final result

The specific business needs are based on the actual needs of our project. I am just doing a rough demonstration here. 

Guess you like

Origin blog.csdn.net/m0_53464000/article/details/132559520