java实现:将Json转为Excel
先来看效果:
json = [{"name":"Alice","age":25,"city":"New York"},{"name":"Bob","age":30,"city":"London"}]
输出excel文件内容:

一. 添加依赖
这里使用阿里云镜像来下载依赖项
将以下内容复制到pom.xml文件中,也可复制Apache POI和JSON库添加到已有的pom.xml中。
4.0.0 com.example json-to-excel 1.0.0 1.8 1.8 aliyun https://maven.aliyun.com/repository/public org.apache.poi poi 4.1.2 org.apache.poi poi-ooxml 4.1.2 org.json json 20210307
二. 实现代码
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONObject;import java.io.FileOutputStream;public class JsonToExcelExporter {public static void main(String[] args) {// 示例JSON数据String jsonString = "[{\"name\":\"Alice\",\"age\":25,\"city\":\"New York\"},{\"name\":\"Bob\",\"age\":30,\"city\":\"London\"}]";JSONArray jsonArray = new JSONArray(jsonString);try {exportJsonToExcel(jsonArray, "D:/output-" + String.valueOf(System.currentTimeMillis()) + ".xlsx");System.out.println("json转excel成功");} catch (Exception e) {e.printStackTrace();}}public static void exportJsonToExcel(JSONArray jsonArray, String filePath) throws Exception {Workbook workbook = new XSSFWorkbook();Sheet sheet = workbook.createSheet("Sheet1");// 创建表头Row headerRow = sheet.createRow(0);JSONObject firstObject = jsonArray.getJSONObject(0);int columnIndex = 0;for (String key : firstObject.keySet()) {Cell cell = headerRow.createCell(columnIndex++);cell.setCellValue(key);}// 填充数据int rowIndex = 1;for (int i = 0; i < jsonArray.length(); i++) {JSONObject jsonObject = jsonArray.getJSONObject(i);Row dataRow = sheet.createRow(rowIndex++);columnIndex = 0;for (String key : jsonObject.keySet()) {Cell cell = dataRow.createCell(columnIndex++);Object keyObject = jsonObject.get(key);// 判断jsonObject中的类型if (keyObject instanceof Integer) {cell.setCellValue(jsonObject.getInt(key));} else if (keyObject instanceof String) {cell.setCellValue(jsonObject.getString(key));} else if (keyObject instanceof JSONArray) {cell.setCellValue(jsonObject.getJSONArray(key).toString());} else if (keyObject instanceof JSONObject) {cell.setCellValue(jsonObject.getJSONObject(key).toString());}}}// 调整列宽for (int i = 0; i < firstObject.length(); i++) {sheet.autoSizeColumn(i);}// 保存Excel文件FileOutputStream fileOut = new FileOutputStream(filePath);workbook.write(fileOut);fileOut.close();workbook.close();}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
