How to Upload and Read a Csv in Grails

Points To Remember


  • Add the plugin Csv Grails plugin .
  • You can do it manually without the plugin if the you have a uniform structure of the csv file.

Upload a Csv 

You need to add the dependency for the csv file reader in BUildConfig.groovy as shown below
BuildConfig.groovy
compile ":csv:0.3.1"
And you have a csv file like the following.

upload.jsp
<g:uploadForm action="upload">
    <input type="file" name="file">
    <g:submitButton name="file" value="Upload"/>
</g:uploadForm>
When the above form is submitted then the request will be handled by the controller action as shown below

UploadController.groovy
def upload() {
        MultipartFile file = request.getFile( 'file' )
        file.inputStream.eachCsvLine { row ->
            String name = row[1] ?: "NA";
            String email = row[2] ?: "NA";

            // Business Logic here
        }
}
Now you can do your business logic in the space provided.

No comments :

Post a Comment