如图,问题是可以根据数据自动生成的,只是举了个栗子,可以把表头headers和内容contents根据数据来生成
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.7.13version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>easyexcelartifactId>
<version>2.2.4version>
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();
}
}
}