JSON转EXCEL
2022/4/22 周五
参考博客 JAVA-JSON文件转excel文件 ,使用的是HSSFWorkbook。
我修改后添加了可生成多个sheet,sheet页名为JSON参数数组的节点名称,可替换节点名称,以及把参数的英文字段名替换为中文表头。
0积分下载demo:JSON转EXCEL
先贴json转excel方法,参数为要生成的文件名路径、要转换的json串、json数组的节点名称(作为生成的sheet页名):
public static void jsonToExcel(String fileName, JSONObject jsonObject, String[] ArrayKeys) throws Exception {
HSSFWorkbook wb = new HSSFWorkbook();
for (String arrayKey : ArrayKeys) {
HSSFSheet sheet = wb.createSheet(ArrayKeys.length > 1 ? arrayKey : "sheet");
Set keys = null;
int rowNo = 0;
HSSFRow row = sheet.createRow(0);
JSONArray jsonArray = jsonObject.getJSONArray(arrayKey);
for (int i = 0; i < jsonArray.size(); i++) {
if (keys == null) {
JSONObject item = jsonArray.getJSONObject(i);
keys = item.keySet();
for (Object s : keys) {
HSSFCell cell = row.createCell(rowNo++);
cell.setCellValue(s.toString());
}
} else {
break;
}
}
for (int i = 0; i < jsonArray.size(); i++) {
rowNo = 0;
JSONObject item = jsonArray.getJSONObject(i);
row = sheet.createRow(i + 1);
keys = item.keySet();
for (Object s : keys) {
HSSFCell cell = row.createCell(rowNo++);
cell.setCellValue(item.getString(s.toString()));
}
}
}
File file = new File(fileName);
file.createNewFile();
FileOutputStream output = new FileOutputStream(fileName);
wb.write(output);
wb.close();
output.flush();
output.close();
}
再给一个调用示例,包括把从数据库查出的英文的字段名替换为中文表头(注意名称不要有重复,否则重复的列就会少,因为被覆盖了):
public static void main(String[] args) throws Exception {
String ret = "这里是JSON串";
System.out.println("接口返回参数:" + ret);
String replace = ret.replaceAll("BY_MONTH_INC", "当月同比").replaceAll("BY_YEAR_INC", "当年同比")
.replaceAll("BY_DATE", "当日(万元)").replaceAll("BY_MONTH", "当月(万元)")
.replaceAll("BY_YEAR", "当年(万元)")
.replaceAll("DATA1", "数据一").replaceAll("DATA2", "数据二");
JSONObject jsonObject = JSONObject.parseObject(replace, Feature.OrderedField);
String[]ArrayKeys = new String[]{"数据一","数据二"};
String fileName = "C:/User/Desktop/test.xlsx";
jsonToExcel(fileName, jsonObject, ArrayKeys);
System.out.println("生成文件成功:"+fileName);
}
测试JSON串如下:
{
"DATA1":[
{
"BY_DATE":"263.38",
"BY_MONTH":"4391.58",
"BY_MONTH_INC":"-27.79%",
"BY_YEAR":"20356.44",
"BY_YEAR_INC":"-14.87%"
},
{
"BY_DATE":"91.81",
"BY_MONTH":"1087.39",
"BY_MONTH_INC":"-27.00%",
"BY_YEAR":"5879.43",
"BY_YEAR_INC":"-12.10%"
},
{
"BY_DATE":"40.29",
"BY_MONTH":"533.51",
"BY_MONTH_INC":"-30.89%",
"BY_YEAR":"2937.50",
"BY_YEAR_INC":"-27.67%"
}
],
"DATA2":[
{
"BY_DATE":"123.38",
"BY_MONTH":"123.58",
"BY_MONTH_INC":"-12.79%",
"BY_YEAR":"12345.44",
"BY_YEAR_INC":"-12.87%"
},
{
"BY_DATE":"12.81",
"BY_MONTH":"1234.39",
"BY_MONTH_INC":"-12.00%",
"BY_YEAR":"1234.43",
"BY_YEAR_INC":"-12.10%"
},
{
"BY_DATE":"98.29",
"BY_MONTH":"987.51",
"BY_MONTH_INC":"-98.89%",
"BY_YEAR":"9876.50",
"BY_YEAR_INC":"-89.67%"
}
]
}
生成的excel:
|