将 for 循环的结果写入 groovy 中的 csv

write the results of for loop to csv in groovy

目前我正在使用 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|0,000.....
filename2|mat_amt|4|orig_price|0,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()

任何帮助都会很棒。

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