TAGS :Viewed: 3 - Published at: a few seconds ago

[ Uploading CSV file and checking its type befor uploading in Groovy/grails ]

I have an application that uploads CSV file for contacts creation. I check before the file uploading whether the file is CSV or not. If it is not CSV then notifies the user to select only CSV files. I do this the following way.

 if (file.getContentType() != "application/vnd.ms-excel") {
       //Notifies the user
                return
 } 

This works perfectly as long as Microsoft Excel is installed on system. How can I do this without MS Excel installed on System ?

Answer 1


You can use following plugin to extract content from file:

http://grails.org/plugin/csv

Then use following code to compare headers of file to an already existing list of headers that you want:

def verifyCsvFile = {file->
    def iWantTheseHeaders=['a','b','c'] //you can get this from config or constants
    file.eachCsvLine { tokens ->


        //First row in the represents the headeres of the csv/xls file. 
        if(index == 0){
            def headers =[]
            tokens.each{
                headers.add(it.trim())
            }

            isValidColumns = headers.containsAll(iWantTheseHeaders)
            // check if Required columns were found 
            if(!isValidColumns){
                return false
            }
        }


    }
}