在日常开发中,有时候我们会将excel中的数据转换为json格式的字符串,标题作为key,行记录作为value字段内容。以下是具体的代码实现:
import cn.hutool.core.map.BiMap;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExcelToJson {
public static void main(String[] args) {
String excelPath = "H:\\Desktop\\test.xlsx";
MyAnalysisEventListener listener = new MyAnalysisEventListener();
EasyExcelFactory.read(excelPath, listener).headRowNumber(0).build().readAll();
List<BiMap> list = listener.getList();
BiMap head = list.remove(0);
Map<String, Integer> inverse = head.getInverse();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < list.size(); i++) {
BiMap biMap = list.get(i);
Map<String, Object> resultMap = new HashMap<>();
for (Map.Entry<String, Integer> entry : inverse.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
resultMap.put(key, biMap.get(value));
}
jsonArray.add(resultMap);
}
System.out.println("result = " + jsonArray.toJSONString());
}
public static class MyAnalysisEventListener extends AnalysisEventListener {
private List<BiMap> list = new ArrayList<>();
@Override
public void invoke(Object data, AnalysisContext context) {
list.add(new BiMap((Map) data));
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
public List<BiMap> getList() {
return list;
}
}
}