Saturday, April 20, 2013

Grails 2.x Excel Import via File Upload

Step 1: Install the excel-import-1.0.0 plugin to your the application you wish to add functionality to.
Step 2: Grails 2.X may throw an error installing the excel-import. simply open application.properties and append "plugins.joda-time=1.3.1" to the file. You may "Resolve Dependencies" or clean depending on your IDE. This seems to be an unresolved bug in the plugin codestream with Grails 2

Now for the code:

index.gsp
(add the following to your view)
<g:form action="upload" method="post" enctype="multipart/form-data">
<label for="file">File:</label>
<input type="file" name="file" id="file" />
<input class="save" type="submit" value="Upload" />


FilesController.groovy:

package edu.harvard.edu
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.grails.plugins.excelimport.*
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
class FilesController {
def excelImportService
def index() {
}
def upload = {

Map CONFIG_BOOK_COLUMN_MAP = [
sheet:'Sheet1',
startRow: 1,
columnMap:  [
      //Col, Map-Key
'A':'val1',
'B':'val2',
'C':'val3',
]
]


MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile file = (CommonsMultipartFile) mpr.getFile("file");

Workbook workbook = WorkbookFactory.create(file.inputStream)
 //Iterate through bookList and create/persists your domain instances
def bookList = excelImportService.columns(workbook, CONFIG_BOOK_COLUMN_MAP)
println bookList
}
}

5 comments: