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

Groovy脚本为CSV字段加引号时出现多余空行求助

Groovy处理CSV添加引号时的格式问题修复

输入CSV文件

0123,00001,00001,01,4.00,T,H,xds,,,,,,,,,,,,,,,
1234,00001,00001,,TI,2024,,4956.00,0.00,,,,,
1234,00001,00001,,TI,2024,,4956.00,0.00,,,,,1234

现有Groovy脚本(存在问题)

def Message processData(Message message) {
    // Retrieve the body of the message as a string (assuming the CSV is in the message body)
    def body = message.getBody(String)

    // Split the body into lines
    def lines = body.split('\n')

    // Enclose each field in double quotes
    def quotedLines = lines.collect { line ->
        line.split(',').collect { field ->
            "\"${field}\""
        }.join(',')
    }

    // Join the quoted lines back together
    def result = quotedLines.join('\n')

    // Set the modified body back to the message
    message.setBody(result)

    return message
}

当前错误输出

"0123","00001","00001","01","4.00","T","H","xds","","","","","","","","","","","","","","","","\n "
 "1234","00001","00001","","TI","2024","","4956.00","0.00","","","","","","\n "
 "1234","00001","00001","","TI","2024","","4956.00","0.00","","","","","","1234"

期望输出

"0123","00001","00001","01","4.00","T","H","xds","","","","","","","","","","","","","","",""
"1234","00001","00001","","TI","2024","","4956.00","0.00","","","","","",""
"1234","00001","00001","","TI","2024","","4956.00","0.00","","","","","","1234"

问题分析与修复方案

问题根源:

  1. 原脚本仅用split('\n')拆分,无法兼容Windows环境的\r\n换行符,还会在输入末尾有换行时生成空行,处理后变成无用的引号行。
  2. 输入行的换行/回车字符可能被错误混入字段,导致输出出现\n这类异常字符。

修改后的脚本:

def Message processData(Message message) {
    def body = message.getBody(String)

    // 兼容Windows/Unix换行符,拆分后过滤空行(含全空格行)
    def lines = body.split(/\r?\n/).findAll { it.trim() != '' }

    def quotedLines = lines.collect { line ->
        line.split(',').collect { field ->
            // 清除字段中混入的换行/回车字符,避免输出异常
            def cleanField = field.replaceAll(/[\r\n]/, '')
            "\"${cleanField}\""
        }.join(',')
    }

    def result = quotedLines.join('\n')

    message.setBody(result)
    return message
}

关键改动说明

  • 用split(/\r?\n/)拆分文本,同时支持Windows和Unix系统的换行格式。
  • 增加findAll { it.trim() != '' }过滤空行,避免无内容的行生成无效的引号行。
  • 对每个字段执行replaceAll(/[\r\n]/, ''),清除混入的换行/回车字符,解决输出中出现\n的问题。

内容的提问来源于stack exchange,提问作者janardhan d

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 07:46:03