首页 > 解决方案 > 在groovy中将for循环的结果写入csv

问题描述

目前我正在使用 Groovy 创建嵌套的 for 循环,将对象的内容打印到一个字符串,该字符串旨在成为分隔数据的行。我想将这些字符串输出到 csv 文件,而不是打印它们。

这是代码:

for (doc in docs) {
    AnnotationSet row = doc.getAnnotations("Final").get("Row")
    AnnotationSet BondCounsel = doc.getAnnotations("Final").get("Bond_Counsel")
    AnnotationSet PurchasePrice = doc.getAnnotations("Final").get("PurchasePrice")
    AnnotationSet DiscountRate = doc.getAnnotations("Final").get("DiscountRate")
    for (b in BondCounsel) {
        for (d in DiscountRate) {
            for (r in row) {
                for (p in PurchasePrice) {
    println(doc.getFeatures().get("gate.SourceURL") + "|"
    + "mat_amount|" + r.getFeatures().get("MatAmount") + "|"
    + "orig_price|" + p.getFeatures().get("VAL") + "|"
    + "orig_yield|" + r.getFeatures().get("Yield") + "|"
    + "orig_discount_rate|" + d.getFeatures().get("rate")+ "|"
    + "CUSIP|" + r.getFeatures().get("CUSIPVAL1") + r.getFeatures().get("CUSIPVAL2") + r.getFeatures().get("CUSIPVAL3") + "|"
    + "Bond_Counsel|" + b.getFeatures().get("value"))
                }
            }
        }
    }
}

其中输出只是一系列字符串,例如:

filename1|mat_amt|3|orig_price|$230,000.....
filename2|mat_amt|4|orig_price|$380,000.....

我知道我可以设置一个文件编写器,即

fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);

<for loop here storing results>
csvFilePrinter.printRecord(forLoopResults)

但我不确定如何正确格式化和存储我当前在 for 循环中打印的内容以便能够传递到csvFilePrinter.printRecord()

任何帮助都会很棒。

标签: javagroovygate

解决方案


printRecord()方法采用 Iterable (每个doc)。例如列表。

因此,在代码的内部循环中,我们将为该行创建一个列表,而不是打印。

具体来说,鉴于此设置:

def FILE_HEADER = ['Bond','Discount','Row','Price']    
def fileName = 'out.csv'

和这个数据聚合(例如):

def BondCounsel = ['bc1','bc2']
def DiscountRate = ['0.1','0.2']
def row = ['r1','r2']
def PurchasePrice = ['p1','p2']

然后这个(编辑:现在制作了 Groovier):

new File(fileName).withWriter { fileWriter ->
    def csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT)
    csvFilePrinter.printRecord(FILE_HEADER)

    BondCounsel.each { b ->
        DiscountRate.each { d ->
            row.each { r ->
                PurchasePrice.each { p ->
                    csvFilePrinter.printRecord([b, d, r, p])
                }
            }
        }
    }
}

会生成这个out.csv

Bond,Discount,Row,Price
bc1,0.1,r1,p1
bc1,0.1,r1,p2
bc1,0.1,r2,p1
... etc

推荐阅读