一、糊涂工具包
1.导入依赖(注:导入的依赖可能会和poi依赖包冲突,导致项目启动不了,我这里poi-ooxml依赖包用的4.1.2版本,可以解决冲突问题)
<!--糊涂工具包--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.16</version> </dependency>
2.生成样式
![](/i/l/?n=22&i=blog/2348148/202211/2348148-20221101201619096-1800880768.png)
3.代码实例
package test;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.*;
@SpringBootTest
public class Demo2 {
@Test
public void test() {
List<String> row1 = CollUtil.newArrayList("aa", "", "", "", "ee", "ff");
List<String> row2 = CollUtil.newArrayList("", "bb1", "", "", "ee1", "ff1");
List<String> row3 = CollUtil.newArrayList("", "", "cc2", "", "ee2", "ff2");
List<String> row4 = CollUtil.newArrayList("aa3", "", "", "", "ee3", "ff3");
List<String> row5 = CollUtil.newArrayList("", "", "", "bb4", "ee4", "ff4");
List<List<String>> rows = CollUtil.newArrayList(row1, row2, row3, row4, row5);
//通过工具类创建writer
ExcelWriter writer = ExcelUtil.getWriter("d:/writeTest1.xlsx");
//通过构造方法创建writer
//ExcelWriter writer = new ExcelWriter("d:/writeTest.xls");
//跳过前2行
writer.passCurrentRow();
writer.passCurrentRow();
//合并单元格后的标题行,使用默认标题样式
writer.merge(0, 1, 0, 3, "表格1", true);
writer.merge(0, 1, 4, 4, "表格2", true);
writer.merge(0, 1, 5, 5, "表格3", true);
//一次性写出内容,强制输出标题
writer.write(rows, true);
//关闭writer,释放内存
writer.close();
}
}
参考文档
官方:https://www.hutool.cn/docs/#/poi/Excel%E7%94%9F%E6%88%90-ExcelWriter
相关文档:https://blog.csdn.net/javaFhx/article/details/124480453
标签:Java,自定义,newArrayList,CollUtil,writer,List,hutool,表头,import From: https://www.cnblogs.com/wj123bk/p/16849031.html