效果图
如图,问题是可以根据数据自动生成的,只是举了个栗子,可以把表头headers和内容contents根据数据来生成
文章来源地址https://www.toymoban.com/news/detail-629423.html
依赖
<!--HuTool工具类-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.13</version>
</dependency>
<!--EasyExcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.4</version>
</dependency>
代码
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.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @author: connie1451
* @copyright:
* @date: 2022/11/25 16:15
* */
class Test2 {
public static void main(String[] args) {
simpleWrite();
}
public static void simpleWrite() {
//Excel文件输的出位置
String outPath = "D:/excel/test2.xlsx";
try {
//创建ExcelWriter写入对象
ExcelWriter excelWriter = EasyExcel.write(new FileOutputStream(outPath)).build();
//创建Sheet对象
WriteSheet sheet = new WriteSheet();
//设置第N个Sheet
sheet.setSheetNo(1);
//设置Sheet名称
sheet.setSheetName("第一个Sheet");
//创建表格对象
WriteTable table = new WriteTable();
//设置第N个表格
table.setTableNo(1);
//创建表头集合
List<List<String>> headList = new ArrayList<List<String>>();
//第N列的表头
List<String> headTitle1 = new ArrayList<>();
List<String> headTitle2 = new ArrayList<>();
List<String> headTitle3 = new ArrayList<>();
List<String> headTitle4 = new ArrayList<>();
List<String> headTitle5 = new ArrayList<>();
List<String> headTitle6 = new ArrayList<>();
List<String> headTitle7 = new ArrayList<>();
headTitle1.add("问卷名称");
//Dau
headTitle2.add("问题一");
headTitle2.add("选项1");
//第三列
headTitle3.add("问题一");
headTitle3.add("选项2");
//第四列
headTitle4.add("问题一");
headTitle4.add("选项3");
//第五列
headTitle5.add("问题二");
headTitle5.add("选项1");
//第六列
headTitle6.add("问题二");
headTitle6.add("选项2");
//第七列
headTitle7.add("问题二");
headTitle7.add("选项3");
headList.add(headTitle1);
headList.add(headTitle2);
headList.add(headTitle3);
headList.add(headTitle4);
headList.add(headTitle5);
headList.add(headTitle6);
headList.add(headTitle7);
table.setHead(headList);
List<List<Object>> contents = new ArrayList<>();
for (int i = 0; i <= 5; i++) {
List<Object> content = new ArrayList<>();
for (int j = 0; j < 7; j++) {
content.add( + i + "行第" + j + "例");
}
contents.add(content);
}
excelWriter.write(contents, sheet, table);
// 记得 释放资源
excelWriter.finish();
System.out.println("ok");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
文章来源:https://www.toymoban.com/news/detail-629423.html
到了这里,关于easyExcel生成动态表头的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!