Add 0 to empty csv cells using Groovy

拥有回忆 提交于 2020-01-07 03:00:32

问题


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.

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>

Any suggestions how to solve this with groovy?

Thanks in advance


回答1:


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 }"
    }
  }


来源:https://stackoverflow.com/questions/41396432/add-0-to-empty-csv-cells-using-groovy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!