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

时间:2018-08-23 22:03:09

标签: java groovy gate

当前,我正在使用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()

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:4)

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