使用 Groovy 将 0 添加到空的 csv 单元格 [英] Add 0 to empty csv cells using Groovy

查看:16
本文介绍了使用 Groovy 将 0 添加到空的 csv 单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 groovy 脚本在 CSV 文件上的 2 个字段之间进行连接.该脚本运行良好,只是它在遇到空单元格时会崩溃.

Im using a groovy script to concatenate between 2 fields on a CSV files. The script is working perfectly except it collapse once it hits empty cells.

我设法使用 powershell 脚本来避免这种情况,但后来我遇到了编码问题

I managed to use a powershell script to avoid this thing but then i got stuck with encoding issue

    <groovy>
  ant.mkdir(dir:"target")


  new File("target/UpsertCheckDeals.csv").withWriter {
    new File("C:/Users/alon\Documents\CheckDealBeforeUpsert.csv").splitEachLine(",") { Customer__c, Name__c, Deal__c, Amount__c, CheckCount__c, Discount__c ->
       it.println "${Customer__c},${Name__c},${CheckCount__c},${Deal__c},${Amount__c},${Discount__c},${Customer__c}-${Deal__c }"
    }
  }

</groovy>

有什么建议可以用 groovy 解决这个问题吗?

Any suggestions how to solve this with groovy?

提前致谢

推荐答案

如果没有关于错误的详细信息,我将假设 splitEachLine 方法无法将行分割成足够多的部分以便分配所有闭包声明的参数的值.

Without details on the error, I'm going to assume the splitEachLine method cannot split the line into enough parts in order to assign values to all of the Closure's declared arguments.

要解决此问题,我将使用单参数闭包.单个参数被分配了一个拆分值的数组(列表?).您可以在尝试处理行之前检查数组的长度.

To workaround this, I would use a single-arg closure. The single argument is assigned an array (List?) of the split values. You can check the length of the array before you attempt to process the row.

new File("target/UpsertCheckDeals.csv").withWriter {
    new File("C:/Users/alon\Documents\CheckDealBeforeUpsert.csv").splitEachLine(",") { parts ->
        if (parts.length != 6) return // or maybe it's .size()
        (Customer__c, Name__c, Deal__c, Amount__c, CheckCount__c, Discount__c) = parts
        it.println "${Customer__c},${Name__c},${CheckCount__c},${Deal__c},${Amount__c},${Discount__c},${Customer__c}-${Deal__c }"
    }
  }

这篇关于使用 Groovy 将 0 添加到空的 csv 单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆