码农包龙星 2025-06-26 15:45 采纳率: 0%
浏览 8

(标签-json|关键词-字符串)

写一个json 转excel 的java代码,要求:用easyExcel , fastjson2, 然后传参可以 是一个文件夹路径或者文件路径,或者一个段jsonArray字符串,json里的key 作为表头,要考虑到多级表头,例如{a:{b:value}}, b就是a的二级表头,有可能有多级,要考虑未来的扩展。

  • 写回答

6条回答 默认 最新

  • 檀越@新空间 2025-06-26 15:46
    关注

    下午好🌅🌅🌅
    本答案参考通义千问

    好的,下面是一个使用 EasyExcelFastJSON2 实现 JSON 转 Excel 的 Java 示例代码。该程序支持以下功能:

    • 接收参数:文件夹路径、文件路径、或 JSON 字符串
    • 将 JSON 中的 key 作为表头,支持多级表头(如 {a: {b: value}}
    • 使用 FastJSON2 解析 JSON 数据
    • 使用 EasyExcel 写入 Excel 文件

    ✅ 功能说明

    📌 支持输入方式:

    1. 单个 JSON 文件路径
    2. 文件夹路径(遍历所有 .json 文件)
    3. 直接传入 JSON 字符串(例如通过 API)

    📌 多级表头处理:

    • 如果 JSON 结构是嵌套的,比如 {a: {b: "value"}},则生成多级表头:a -> b
    • 可以扩展为任意层级

    🛠️ 依赖引入(Maven)

    <dependencies>
        <!-- FastJSON2 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.34</version>
        </dependency>
    
        <!-- EasyExcel -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.3.2</version>
        </dependency>
    </dependencies>
    

    🧩 核心类设计

    1. JSONToExcelConverter.java

    import com.alibaba.fastjson2.JSON;
    import com.alibaba.fastjson2.JSONObject;
    import com.alibaba.fastjson2.JSONArray;
    import com.alibaba.fastjson2.TypeReference;
    
    import com.alibaba.easyexcel.EasyExcel;
    import com.alibaba.easyexcel.write.metadata.WriteSheet;
    
    import java.io.*;
    import java.nio.file.*;
    import java.util.*;
    
    public class JSONToExcelConverter {
    
        public static void main(String[] args) {
            String inputPath = "path/to/your/json/file.json"; // 或文件夹路径,或直接JSON字符串
            String outputFilePath = "output.xlsx";
    
            try {
                if (Files.exists(Paths.get(inputPath))) {
                    if (Files.isRegularFile(Paths.get(inputPath))) {
                        processJsonFile(inputPath, outputFilePath);
                    } else if (Files.isDirectory(Paths.get(inputPath))) {
                        processJsonFolder(inputPath, outputFilePath);
                    }
                } else {
                    // 假设输入是 JSON 字符串
                    processJsonString(inputPath, outputFilePath);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private static void processJsonFile(String filePath, String outputFilePath) throws Exception {
            String jsonContent = new String(Files.readAllBytes(Paths.get(filePath)));
            processJson(jsonContent, outputFilePath);
        }
    
        private static void processJsonFolder(String folderPath, String outputFilePath) throws Exception {
            List<String> jsonStrings = new ArrayList<>();
            Files.walk(Paths.get(folderPath))
                 .filter(path -> path.toString().endsWith(".json"))
                 .forEach(path -> {
                     try {
                         jsonStrings.add(new String(Files.readAllBytes(path)));
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                 });
    
            processJsonList(jsonStrings, outputFilePath);
        }
    
        private static void processJsonString(String jsonString, String outputFilePath) {
            processJson(jsonString, outputFilePath);
        }
    
        private static void processJson(String jsonStr, String outputFilePath) {
            JSONObject jsonObject = JSON.parseObject(jsonStr);
    
            List<List<String>> headers = new ArrayList<>();
            List<List<Object>> data = new ArrayList<>();
    
            buildHeadersAndData(jsonObject, "", headers, data);
    
            WriteSheet sheet = EasyExcel.writerSheet("Sheet1").head(headers).build();
            EasyExcel.write(outputFilePath).sheet("Sheet1").doWrite(data);
        }
    
        private static void processJsonList(List<String> jsonStrings, String outputFilePath) {
            List<List<String>> headers = new ArrayList<>();
            List<List<Object>> data = new ArrayList<>();
    
            for (String jsonStr : jsonStrings) {
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                buildHeadersAndData(jsonObject, "", headers, data);
            }
    
            WriteSheet sheet = EasyExcel.writerSheet("Sheet1").head(headers).build();
            EasyExcel.write(outputFilePath).sheet("Sheet1").doWrite(data);
        }
    
        private static void buildHeadersAndData(JSONObject obj, String prefix, List<List<String>> headers, List<List<Object>> data) {
            Map<String, Object> map = obj.getInnerMap();
    
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
    
                String currentKey = prefix.isEmpty() ? key : prefix + "." + key;
    
                if (value instanceof JSONObject) {
                    buildHeadersAndData((JSONObject) value, currentKey, headers, data);
                } else if (value instanceof JSONArray) {
                    JSONArray array = (JSONArray) value;
                    for (int i = 0; i < array.size(); i++) {
                        buildHeadersAndData(array.getJSONObject(i), currentKey, headers, data);
                    }
                } else {
                    // 添加字段到表头和数据中
                    List<String> headerRow = new ArrayList<>();
                    String[] keys = currentKey.split("\\.");
                    for (String k : keys) {
                        headerRow.add(k);
                    }
                    headers.add(headerRow);
    
                    List<Object> rowData = new ArrayList<>();
                    rowData.add(value);
                    data.add(rowData);
                }
            }
        }
    }
    

    ✅ 使用示例

    示例 JSON(单个文件):

    {
      "name": "John",
      "age": 30,
      "address": {
        "city": "Beijing",
        "country": "China"
      },
      "hobbies": [
        {"name": "reading", "level": "high"},
        {"name": "gaming", "level": "medium"}
      ]
    }
    

    输出 Excel 表头:

    | name | age | address.city | address.country | hobbies.name | hobbies.level | |------|-----|--------------|------------------|--------------|----------------|


    📝 注意事项

    1. 多级表头处理:使用 . 分隔不同层级的键。
    2. 数组处理:对于数组中的对象,会将其展开成独立行。
    3. 扩展性:可以通过修改 buildHeadersAndData() 方法来支持更复杂的结构(如嵌套数组、混合类型等)。

    ✅ 总结

    ✅ 关键点总结:

    1. 使用 FastJSON2 解析 JSON 数据。
    2. 使用 EasyExcel 写入 Excel 文件。
    3. 支持多种输入方式:文件路径、文件夹路径、JSON 字符串。
    4. 支持多级表头,可扩展为任意层级结构。
    5. 自动将数组中的对象展开为多行

    如果你有进一步的需求,比如导出为 xlsx、设置样式、分页写入等,也可以继续扩展这个类。需要我帮你实现这些吗?

    评论

报告相同问题?

问题事件

  • 创建了问题 6月26日