需求:将两块数据,写入要一个excel里面。
根据项目,导入依赖版本
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
1、创建对象,用于不同数据接收
import com.alibaba.excel.annotation.ExcelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@Schema(description = "")
public class ExecuteVo {
private static final long serialVersionUID = 1L;
@Schema(description = "")
@ExcelProperty("")
private String indexName;
@Schema(description = "")
@ExcelProperty("")
private String name1;
@Schema(description = "")
@ExcelProperty("")
private String name2;
}
import com.alibaba.excel.annotation.ExcelProperty;
import com.ewx.starinet.archsys.entity.SysBusinessTreenodes;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
@Data
@Schema(description = "")
public class YearCheckedVo {
private static final long serialVersionUID = 1L;
@Schema(description = "")
@ExcelProperty("")
private String indexName;
@Schema(description = "")
@ExcelProperty("")
private String name1;
@Schema(description = "")
@ExcelProperty("")
private String name2;
@Schema(description = "")
@ExcelProperty("")
private String name3;
@Schema(description = "")
@ExcelProperty("")
private String name4;
@Schema(description = "")
@ExcelProperty("")
private String name5;
}
2、具体实现
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class Tests {
public static void main(String[] args) throws IOException {
// 文件保存地址
String path = ;
File file = new File(path);
// 不存在目录就创建目录
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
File file1 = new File(path + "s.xls");
if(!file1.exists()){
file1.createNewFile();
}
List<ExecuteVo> list1 = 实体1;
List<YearCheckedVo> list2 = 实体2;
ExcelWriter excelWriter = null;
try {
excelWriter = EasyExcel.write(file1).build();
// 把sheet设置为不需要头 不然会输出sheet的头 这样看起来第一个table 就有2个头了
WriteSheet writeSheet = EasyExcel.writerSheet().needHead(Boolean.FALSE).build();
// 这里必须指定需要头,table 会继承sheet的配置,sheet配置了不需要,table 默认也是不需要
WriteTable writeTable1 = EasyExcel.writerTable(0).head(DemoVo1.class).needHead(Boolean.TRUE).build();
// 第二个对象 读取对象的excel实体类中的标题
WriteTable writeTable2 = EasyExcel.writerTable(1).head(DemoVo2.class).needHead(Boolean.TRUE).build();
// 第一次写入会创建头
excelWriter.write(list1, writeSheet, writeTable1);
// 第二次写如也会创建头,然后在第一次的后面写入数据
excelWriter.write(list2, writeSheet, writeTable2);
}finally {
if (excelWriter != null) {
excelWriter.finish();
}
}
}
}
需要注意的是这里
excelWriter.finish();
结束的时候文件里面才会出现内容