java json 写入excel_用java解析从接口获取json内容并用XSSFWorkbook写到excel(.xlsx)

本文介绍了一个Java程序,该程序使用Apache POI库来创建Excel文件,并填充由JSON接口返回的数据。程序首先定义了Excel文件的标题行,然后通过调用特定的方法获取JSON格式的StationInfos内容,并将其逐条写入Excel中。
摘要由CSDN通过智能技术生成

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;importjava.util.Iterator;public classOperExcel {public static voidmain(String[] args) {

String stationInfo_title[]={"Pictures","StationLng","SiteGuide","Address","ServiceTel","SupportOrder","OperatorID","StationID","Remark","StationName","StationTel","StationLat","StationStatus","CountryCode","StationType","EquipmentOwnerID","Construction","MatchCars","ParkFee","ParkInfo","ServiceFee","Payment","ElectricityFee","AreaCode","EquipmentInfos","ParkNums","BusineHours"};//创建excel工作薄

XSSFWorkbook workbook = newXSSFWorkbook();//创建一个工作表sheet

XSSFSheet sheet = workbook.createSheet("stationInfo");//创建第一行

XSSFRow row = sheet.createRow(0);//创建一个单元格

XSSFCell cell = null;//插入第一行标题栏

for (int i=0;i

cell=row.createCell(i);

cell.setCellValue(stationInfo_title[i]);

}//接着写入内容

StarStationInfoToExcel starStationInfoToExcel = newStarStationInfoToExcel();try{//通过接口获取StationInfos内容,json格式,用java解析

JSONObject stationInfosJason =starStationInfoToExcel.getStationInfo();int pageNo = (int)stationInfosJason.get("PageNo");int pageCount = (int)stationInfosJason.get("PageCount");int itemSize =(int)stationInfosJason.get("ItemSize");

System.out.println("pageNo:"+pageNo);

System.out.println("pageCount:" +pageCount);

System.out.println("itemSize:" +itemSize);

JSONArray stationInfosJasonArray= stationInfosJason.getJSONArray("StationInfos");for(int i=0;i

row= sheet.createRow(i+1);//先写行数据,从第二行开始写

JSONObject jasonObject =stationInfosJasonArray.getJSONObject(i);

Iterator stationInfoKeys=jasonObject.keySet().iterator();while(stationInfoKeys.hasNext()) {

String key=(String) stationInfoKeys.next();

String value=(String) jasonObject.getString(key);

cell= row.createCell(colunm); //先建单元格,从0开始

cell.setCellValue(value); //给单元格赋值

colunm ++;

}

}

}catch(Exception e) {

e.printStackTrace();

}//创建一个文件

File file = new File("D:\\javaExample\\file\\stationInfo.xlsx");try{if(!file.exists()) {

file.createNewFile();

}//创建输出流

OutputStream outputStream = newFileOutputStream(file);//将拼好的Excel写入到文件流

workbook.write(outputStream);//关闭输出流

outputStream.close();

}catch(Exception e) {

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值