packagejansonDemo;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONArray;importcom.alibaba.fastjson.JSONObject;importorg.apache.poi.xssf.usermodel.XSSFCell;importorg.apache.poi.xssf.usermodel.XSSFRow;importorg.apache.poi.xssf.usermodel.XSSFSheet;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;importjava.io.File;importjava.io.OutputStream;importjava.io.FileOutputStream;import java.util.*;public classTestJsonToExcel {public static voidmain(String[] args) {
XSSFWorkbook workbook;
XSSFSheet sheet;
XSSFRow row;
XSSFCell cell;//创建excel工作薄
workbook = newXSSFWorkbook();//创建一个工作表sheet
sheet = workbook.createSheet("stationInfo");//创建第一行
row = sheet.createRow(0);//创建一个单元格
cell = null;//定义标题栏,放到数组中
String stationInfo_title[] ={"Pictures","StationLng","SiteGuide","Address","ServiceTel","SupportOrder","OperatorID","StationID","Remark"};//在第一行插入标题栏
for (int i=0;i
cell=row.createCell(i);
cell.setCellValue(stationInfo_title[i]);
}//接着从第二行开始写入内容://根据标题栏中的字段筛选相应的值,并非是获取所有接口返回的值
CommonFunc cf = newCommonFunc();try{int rownum = 1;
String cellContent= "";
JSONObject decrptobj= cf.getStationInfo(); //获取从接口返回的json对象
JSONArray stationArray = decrptobj.getJSONArray("StationInfos");
JSONArray sortedstationArray= sortJsonArray(stationArray,"StationID"); //调用排序方法,对json数组中的对象排序
for (int j=0; j
row= sheet.createRow(rownum); //json数组中有多少对象就依次为每个对象创建一行
JSONObject bodyObj =sortedstationArray.getJSONObject(j);for (int k=0; k
cellContent=bodyObj.getString(stationInfo_title[k]);
cell= row.createCell(k); //创建单元格,即生成每行对应的列,新的一行每个单元格从0计数
cell.setCellValue(cellContent); //给每行的单元格赋值,组成每列的值
}
rownum++;
}
}catch(Exception e) {
e.printStackTrace();
}//创建一个文件
File file = new File("D:\\javaExample\\file\\stationInfo.xlsx");try{if(!file.exists()) {
file.createNewFile();
}//创建输出流
OutputStream outputStream = newFileOutputStream(file);//将拼好的内容通过输出流写到excle
workbook.write(outputStream);//关闭输出流
outputStream.close();
}catch(Exception e) {
e.printStackTrace();
}
}//专门写一个对JSONArray排序的方法
public static JSONArray sortJsonArray(JSONArray jsonArray, finalString sortKey) {
List list = new ArrayList<>();for (int i=0; i
list.add(jsonArray.getJSONObject(i));
}
Collections.sort(list,new Comparator() {
String key=sortKey;
@Overridepublic intcompare(JSONObject o1, JSONObject o2) {
String str1=o1.getString(key);
String str2=o2.getString(key);returnstr1.compareTo(str2);
}
});//先清空原有数组
jsonArray.clear();//将排序好的JSONObject放到JSONArray里
for (int j=0; j
jsonArray.add(list.get(j));
}returnjsonArray;
}
}