引入jar
java
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.0</version>
</dependency>
代码
java
public static void main(String[] args) {
//选择存储地址
String fileName = "/Users/qweasdzxc/Downloads/text.xlsx";
// 创建ExcelWriterBuilder对象
ExcelWriter excelWriter = EasyExcelFactory.write(fileName).build();
//设置动态表头
List<List<String>> head1 =new ArrayList<>();
head1.add(Collections.singletonList("姓名"));
head1.add(Collections.singletonList("年龄"));
head1.add(Collections.singletonList("性别"));
//填充数据
List<List<Object>> data1 = new ArrayList<>();
data1.add(Arrays.asList("张三", 20, "男"));
data1.add(Arrays.asList("李四", 25, "女"));
//放入sheet1中
//automaticMergeHead 控制是否合并相同标题的单元格 false==不合并
WriteSheet writeSheet = EasyExcelFactory.writerSheet(0, "学生信息1").head(head1).automaticMergeHead(false).build();
excelWriter.write(data1, writeSheet);
List<List<String>> head2 =new ArrayList<>();
head2.add(Collections.singletonList("学科"));
head2.add(Collections.singletonList("分数"));
List<List<Object>> data2 = new ArrayList<>();
data2.add(Arrays.asList("数学", 90));
data2.add(Arrays.asList("英语", 85));
//放入sheet2中
writeSheet = EasyExcelFactory.writerSheet(1, "学生信息2").head(head2).build();
excelWriter.write(data2, writeSheet);
//关流
excelWriter.finish();
}