package com.example.springboottest;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
/**
* @author hesh
* @title: excel工具
* @projectName springcloud
* @description: TODO
* @date 2021/11/183:40 下午
*/
@SpringBootTest(classes = EasyExcelTest.class)
public class EasyExcelTest {
/**
* @description: sheet表格数据转JSON数据
* @author hesh
* @date 2021/11/18 4:45 下午
*/
@Test
public JSONArray excelImport(String fileName , int sheetNum) throws FileNotFoundException {
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
List<Object> list = EasyExcelFactory.read(fileInputStream, new Sheet(sheetNum));
String listString = JSONObject.toJSONString(list);
JSONArray arryList = JSONObject.parseArray(listString);
JSONArray temp = null;
JSONArray header = JSON.parseArray(arryList.get(0).toString());
JSONArray result = new JSONArray();
for(int i = 1 ; i < arryList.size() ; i++){
temp = JSON.parseArray(arryList.get(i).toString());
JSONObject index = new JSONObject();
for(int j = 0 ; j < header.size() ; j ++){
index.put(header.get(j).toString(),temp.get(j));
}
if(!index.isEmpty() && index.get(header.get(0).toString()) != null && !index.get(header.get(0).toString()).equals("")){
result.add(index);
}
}
System.out.println(result.toJSONString());
return result;
}
}
easy excel 将excel sheet页数据转json数据
最新推荐文章于 2024-06-14 11:20:36 发布