如何将结果映射遍历为CSV文件?
当我将方法放在 Controller 块中时,可以很好地进行迭代,但是如果将其放在服务中并调用,它将无法识别键并返回空行。 (无法识别it.column_1。)

class someController {
    def someService

    def export(Person personInstance) {
        def resultRows = someService.result(personInstance)

        response.setHeader("Content-disposition", "attachment; filename=sample.csv")
        response.contentType = "application/vnd.ms-excel"

        def outs = response.outputStream

        outs << "${personInstance}\n"
        outs << "Column1,Column2,Column3,Column4\n"

        resultRows.each() {
            outs << it.column_1 + "," + it.column_2 + "," + it.column_3 + "," + it.column_4
            outs << "\n"
        }
        outs.flush()
        outs.close()
    }
}

先感谢您。

编辑
我已经包含了有效的代码。

当我在someService.result之后立即在控制台中打印resultRows时,我得到了

[[column_1:John,column_2:Doe,column_3:123 Main Street,column_4:(123)456-7890] [column_1:John,column_2:Doe,column_3:123 Main Street,column_4:(123)456-7890]]

通过以下代码,我得到了可下载的excel格式的CSV文件。
class someController {

    def export(Person personInstance) {
        def sql = new Sql(dataSource)
        def resultRows = sql.rows('select * from table where person_id = ?', [personInstance.id])

        [resultRows:resultRows]

        response.setHeader("Content-disposition", "attachment; filename=sample.csv")
        response.contentType = "application/vnd.ms-excel"

        def outs = response.outputStream

        outs << "${personInstance}\n"
        outs << "Column1,Column2,Column3,Column4\n"

        resultRows.each() {
            outs << it.column_1 + "," + it.column_2 + "," + it.column_3 + "," + it.column_4
            outs << "\n"
        }
        outs.flush()
        outs.close()
    }
}

编辑-找到答案

啊,我知道了问题所在。我在服务内部有[resultRows:resultRows]。我删除了该行,并将其放在def resultRows行下的 Controller 中。
def export(Person personInstance) {
    def resultRows = someService.result(personInstance)
    [resultRows:resultRows]
....
}

感谢你们!

最佳答案

啊,我知道了问题所在。我在服务内部有[resultRows:resultRows]。我删除了该行,并将其放在def resultRows行下的 Controller 中。

def export(Person personInstance) {
    def resultRows = someService.result(personInstance)
    [resultRows:resultRows]
....
}

感谢你们!

10-08 04:36