这里的需求是,如果表格不存在,则新建表格,并填入数据,如果表格存在,那么就追加内容,并且支持单元格合并。
内容追加,需要分两种方式插入,第一种就是没有表格,需要生成表头,并且插入内容,第二种就是已经有了表格,这个表格作为模板并,不用设置表头,直接追加内容,这里需要生成一个新的表格,如果有必要,最后还要删除老的表格。
关于单元格合并,网上有这样的示例,使用easyexcel来实现,我们就是需要定义一个CellWriteHandler的接口实现,在实现类中,覆盖afterCellDispose()方法,本例中就是CustomCellWriteHandler类。
这里为了验证我们的结果,我们利用springboot构建两个不同的请求,一个是创建excel,一个是追加excel。
主要代码如下:
依赖文件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel-core</artifactId>
<version>3.2.1</version>
</dependency>
控制器类:
import com.example.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/excel")
public class ExcelController {
@Autowired
private ExcelService excelService;
@GetMapping("/create")
public ResponseEntity create() {
return ResponseEntity.ok(excelService.create());
}
@GetMapping("/append")
public ResponseEntity append() {
return ResponseEntity.ok(excelService.append());
}
}
服务类:
package com.example.service;
import com.alibaba.excel.EasyExcel;
import com.example.config.CustomCellWriteHandler;
import com.example.dao.ExcelDao;
import com.example.model.ExcelData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
@Service
public class ExcelService {
@Autowired
private ExcelDao excelDao;
pr