Excel 如图所示
结果展示
[{"children":[{"value":"value","key":"key"},{"value":"value","key":"key"},{"children":[{"value":"value","key":"key"},{"value":"value","key":"key"},{"value":"value","key":"key"}],"value":"value","key":"key"},{"children":[{"value":"value","key":"key"},{"value":"value","key":"key"},{"children":[{"value":"value","key":"key"},{"value":"value","key":"key"}],"value":"value","key":"key"}],"value":"value","key":"key"}],"value":"value","key":"key"}]
话不多说,上代码
pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.4</version>
</dependency>
code
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import java.io.File;
import java.util.*;
public class Excel2Json {
public static void main(String[] args) {
List<LinkedHashMap<Integer,String>> list = EasyExcel.read(new File("C:\\Users\\lee\\Desktop\\test.xls")).sheet(0).headRowNumber(0).doReadSync();
System.out.println(list);
JSONArray jsonArray = new JSONArray();
List<String> pathList = new ArrayList<>();
Map<String, JSONObject> mark = new HashMap<>();
for (LinkedHashMap<Integer,String> integerStringLinkedHashMap : list) {
int i = 0;
while (true) {
String str = integerStringLinkedHashMap.get(i);
String path = "";
// if (StringUtils.isNotBlank(str)) {
if (str!=null) {
String[] strings = str.split(":");
String[] keys = new String[2];
String key = strings[0];
if (pathList.size()<=i) {
pathList.add("0");
} else {
pathList.set(i,"0");
}
for (int j=0;j<=i;j++) {
String p = pathList.get(j);
path += p;
if (j<i) {
path += ".children.";
}
}
path = "$."+path;
String faPath = path.substring(0,path.lastIndexOf("children") == -1?path.length():path.lastIndexOf("children")+8);
JSONArray currentArray = null;
if (i == 0) {
currentArray = jsonArray;
} else {
currentArray = (JSONArray) JSONPath.eval(jsonArray, faPath);
}
if (currentArray != null) {
if (i == 0) {
faPath = "$";
}
path = faPath+"."+(currentArray.size());
String oldKey = pathList.get(i);
oldKey = String.valueOf(currentArray.size());
pathList.set(i,oldKey);
}
path += ".value";
String value = strings[1];
System.err.println(path);
System.err.println(i+" "+str);
JSONPath.set(jsonArray, path, value);
path = path.replace(".value",".key");
JSONPath.set(jsonArray, path, key);
break;
}
i++;
}
}
System.err.println(jsonArray.toJSONString());
}
}
基本逻辑
1.遍历每一行每一列,标记好位置信息
2.利用 JSONPath 拼装成 json