前言
在最近的工作中,由于导入模板除了前三列(姓名、手机号、实发工资)固定;其余的列不固定,并且可以做到两个模板的数据都能够正常入库进行对应业务处理。
一、数据模板数据展示:
(1)模板一
(2)模板二
二、处理思路
观察两个模板的数据;结合面向对象的编程思想设计;我可以将两模板需要的获取的字段属性归纳为5个属性点:
注意:标题头在以下中不算!!!
索引(index)-- 相当于excel中所在列的下标列索引
列名称(name)-- 相当于excel中所在列的名称
列值(value)-- 相当于excel中所在列的值
是否存在合并单元格(isGrossField)-- 相当于excel中所在列的是否有合并单元格
合并的子元素(child)-- 相当于excel中所在列的是否有合并单元格下所包含的列
三、编程准备
1、实体类创建:
/**
* @project
* @Description
* @Author songwp
* @Date 2022/8/17 9:04
* @Version 1.0.0
**/
@Data
public class TreeExcel implements Serializable {
private int index = 0;
private String name;
private String value;
private boolean isGrossField;
private List childs;
}
2、maven依赖的引入
<dependency>
<groupId>com.alibabagroupId>
<artifactId>easyexcelartifactId>
<version>2.2.0-beta2version>
dependency>
3、文件解析工具类的编写
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSONArray;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @project
* @Description
* @Author songwp
* @Date 2022/8/17 9:09
* @Version 1.0.0
**/
public class ExcelUtil {
private String value = "empty";
private List nodes;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void createExcelJson(List treeExcelList, int valueQueueSize, Queue linkedValue, boolean firstStorey) {
if (null != nodes && !firstStorey) {
TreeExcel treeExcel = new TreeExcel();
treeExcel.setGrossField(true);
treeExcel.setName(treeExcel.getName());
treeExcel.setIndex(valueQueueSize - linkedValue.size());
List listElem = new ArrayList<>();
treeExcel.setChilds(listElem);
for (ExcelUtil tree : nodes) {
tree.createExcelJson(listElem, valueQueueSize, linkedValue, false);
}
treeExcelList.add(treeExcel);
} else {
if (firstStorey) {
for (ExcelUtil tree : nodes) {
tree.createExcelJson(treeExcelList, valueQueueSize, linkedValue, false);
}
return;
}
TreeExcel treeExcel = new TreeExcel();
treeExcel.setIndex(valueQueueSize - linkedValue.size());
treeExcel.setName(treeExcel.getName());
treeExcel.setValue(linkedValue.poll());
treeExcel.setGrossField(false);
treeExcelList.add(treeExcel);
}
}
/**
* 获取树状数据结构
*
* @param inputStream
* @return
* @throws Exception
*/
public static JSONArray getExcelParseJSON(InputStream inputStream) throws Exception {
List