Groovy load .csv files

前端 未结 6 647
孤城傲影
孤城傲影 2020-12-23 20:01

How to read and import .csv file in groovy on grails. I have .csv file with data and
need to import in to db using user interface .

6条回答
  •  余生分开走
    2020-12-23 20:54

    I prefer a slight tweak on the accepted answer: zip the columns and values together, as opposed to indexing each one by number. The result is slightly shorter code.

    def sql = Sql.newInstance("jdbc:mysql://localhost:3306/mydb", "user", "pswd", "com.mysql.jdbc.Driver")
    def people = sql.dataSet("PERSON")
    def columns = ['first_name', 'last_name', 'email']
    new File("users.csv").splitEachLine(",") {values ->
        people.add([columns, values].transpose().collectEntries())
    }
    

提交回复
热议问题