代码拉取完成,页面将自动刷新
基于POI开发
<properties>
<poi.version>3.15</poi.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
- 主要代码包括两个Java类(TemplateExcelUtils.java 和 Table.java)
- TemplateExcelUtils.java为只要逻辑代码,建议放在utils包下
- Table.java为添加表数据的实体类,建议放在common包下面
{{name}} | {{title}} | |
---|---|---|
{{#table1#}} |
//通过文件系统的方式, 最大扫描行,最大扫描列
TemplateExcelUtils.builder()
.setFileSystemTemplate("D:/template.xlsx", 2, 3);
//在web环境下的方式, 最大扫描行,最大扫描列
TemplateExcelUtils.builder().
.setClassTemplatePath("/template.xlsx", 2, 3);
//添加键值数据
Map<String, String> data = new HashMap<>();
data.put("name", "xiaoming");
data.put("title", "The title");
TempalteExcelUtils.builder().
.setFileSystemTemplate("D:/template.xlsx", 2, 3)
.addValueData(data);
Table.java
public class Table{
//键序列, 通过这个序列依次再rowDataList中取值
private List<String> keySequence;
//表头数据
private List<String> headers;
//行数据
private List<Map<String, String>> rowDataList;
public Table(List<String> keySequence, List<String> headers, List<Map<String, String>> rowDataList) {
this.keySequence = keySequence;
this.headers = headers;
this.rowDataList = rowDataList;
}
public Table(List<String> keySequence, List<Map<String, String>> rowDataList) {
this.keySequence = keySequence;
this.rowDataList = rowDataList;
}
/**
* getter/setter
*/
}
添加表格数据
//......
//实例表格数据
List<Map<String, String>> rows = new ArrayList<>();
Map<String, String> row = new HashMap<>();
row.put("field1", "data1");
row.put("field2", "data2");
rows.add(row);
Table table = new Table(Arrays.asList("field1", "field2"), rows);
TempalteExcelUtils.builder().
.setFileSystemTemplate("D:/template.xlsx", 2, 3)
.addValueData(data)
.addMergerTableData("table1", table);
/**
* 一次调用addMergerTableData 添加表数据,则是将这些表格数据合并;
* 多次调用addMergerTableData 添加表数据,则是分别添加。
* addMergerTableData(String tableName, Table... table);
*/
//...
//调用build构建excel
TempalteExcelUtils.builder().
.addValueData(data);
.addMergerTableData("table1", table);
.build()
//...
OutputStream out = new FileOutputStream("D:/new.xlsx");
TempalteExcelUtils.builder().
.addValueData(data);
.addMergerTableData("table1", table);
.build()
.export(out);
xiaoming | The title | |
---|---|---|
data1 | data2 |
在web环境中将 TemplateExcelUtils.java中的注释打开,导入需要的包
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。