You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Groovy代码将JSON数据转换为CSV/Excel格式文件

Groovy 实现JSON转CSV/Excel具体方案

输入JSON样例

{
    "BRANCH": "master",
    "name": "customer",
    "product_name" : "PQ",
    "domain" : "Shopping",
    "_id": "12345"
}

注:以下方案同时支持单条JSON、JSON数组格式的输入文件。


方案1:转CSV(纯Groovy实现,无额外依赖)

直接用Groovy内置的JsonSlurper解析JSON,手动拼接CSV格式内容,自带特殊字符转义逻辑:

import groovy.json.JsonSlurper

// 1. 配置输入输出路径
def inputJsonPath = "你的输入JSON文件路径.json"
def outputCsvPath = "输出的CSV文件路径.csv"

// 2. 解析JSON
def jsonSlurper = new JsonSlurper()
def jsonContent = new File(inputJsonPath).text
def data = jsonSlurper.parseText(jsonContent)
// 如果是单条JSON,统一转成列表处理
data = data instanceof List ? data : [data]

if(data.isEmpty()){
    println "JSON文件无有效数据"
    return
}

// 3. 提取CSV表头(取第一条数据的key)
def headers = data[0].keySet() as List

// 4. 生成CSV内容,处理字段含逗号/引号的转义
def csvLines = []
csvLines.add(headers.join(","))
data.each { row ->
    def lineItems = headers.collect { key ->
        def value = row[key]?.toString() ?: ""
        // 字段包含逗号/双引号/换行符时,用双引号包裹,内部双引号转义为两个双引号
        if(value.contains(",") || value.contains('"') || value.contains("\n")){
            value = '"' + value.replace('"', '""') + '"'
        }
        return value
    }
    csvLines.add(lineItems.join(","))
}

// 5. 写入CSV文件
new File(outputCsvPath).write(csvLines.join("\n"), "UTF-8")
println "CSV文件生成成功,路径:${outputCsvPath}"

方案2:转Excel(基于Apache POI,支持复杂格式)

如果需要生成标准Excel(xlsx格式),先引入Apache POI依赖,再调用API生成:

依赖配置(Gradle示例)

dependencies {
    implementation 'org.apache.poi:poi-ooxml:5.2.5'
}

转换代码

import groovy.json.JsonSlurper
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.FileOutputStream

// 1. 配置输入输出路径
def inputJsonPath = "你的输入JSON文件路径.json"
def outputExcelPath = "输出的Excel文件路径.xlsx"

// 2. 解析JSON
def jsonSlurper = new JsonSlurper()
def jsonContent = new File(inputJsonPath).text
def data = jsonSlurper.parseText(jsonContent)
data = data instanceof List ? data : [data]

if(data.isEmpty()){
    println "JSON文件无有效数据"
    return
}

// 3. 初始化Excel工作簿、工作表
def workbook = new XSSFWorkbook()
def sheet = workbook.createSheet("数据Sheet")

// 4. 写表头行
def headers = data[0].keySet() as List
def headerRow = sheet.createRow(0)
headers.eachWithIndex { header, index ->
    headerRow.createCell(index).setCellValue(header)
}

// 5. 写数据行
data.eachWithIndex { rowData, rowIndex ->
    def dataRow = sheet.createRow(rowIndex + 1)
    headers.eachWithIndex { key, colIndex ->
        def value = rowData[key]?.toString() ?: ""
        dataRow.createCell(colIndex).setCellValue(value)
    }
}

// 6. 自适应列宽(可选)
headers.eachWithIndex { _, index ->
    sheet.autoSizeColumn(index)
}

// 7. 写入Excel文件
def outputStream = new FileOutputStream(outputExcelPath)
workbook.write(outputStream)
outputStream.close()
workbook.close()
println "Excel文件生成成功,路径:${outputExcelPath}"

内容的提问来源于stack exchange,提问作者mahadeo rajak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:45:01