JSONObject object= JSON.parseObject(result);
JSONObject departmentSharingRequestPackageDTO=object.getJSONObject("data");
JSONArray jsonArray=departmentSharingRequestPackageDTO.getJSONArray("list");
List<JSONObject> list = JSONObject.parseArray(jsonArray.toJSONString(), JSONObject.class);
Set keys = null;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet0");
int roleNo = 0;
int rowNo = 0;
for(JSONObject jsonObject:list){
HSSFRow row = sheet.createRow(roleNo++);
if (keys == null) {
keys = jsonObject.keySet();
for (Object s : keys) {
HSSFCell cell = row.createCell(rowNo++);
cell.setCellValue(s.toString());
}
rowNo = 0;
row = sheet.createRow(roleNo++);
}
for (Object s : keys) {
HSSFCell cell = row.createCell(rowNo++);
cell.setCellValue(jsonObject.getString((String) s));
}
rowNo = 0;
}
FileOutputStream output = new FileOutputStream("/data/file/target.xls");
wb.write(output);
wb.close();
output.flush();
output.close();
FileInputStream fileInputStream = new FileInputStream("/data/file/target.xls");
String encodedFileName = URLEncoder.encode(departmentSearchResultParam.getInterfaceId(), "utf-8");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;fileName=" + encodedFileName);
ServletOutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
while (fileInputStream.read(buffer) != -1) {
outputStream.write(buffer);
}
log.info("下载完成");
outputStream.flush();
outputStream.close();
JAVA将JSON写入excel
最新推荐文章于 2024-08-07 19:31:05 发布
该代码段展示了如何将JSON数据解析成Java对象,进一步转化为列表,并创建Excel文件进行数据导出。主要涉及JSONObject、JSONArray、HSSFWorkbook等库的操作,实现了从JSON到Excel的转换过程。
摘要由CSDN通过智能技术生成