Friday, 13 January 2017

Read files of .csv, .xlsx and .xls in Groovy

Needed jars: poi-3.7.jar poi-ooxml-3.6-20100309.jar poi-ooxml-schemas-3.6-20100309.jar xmlbeans-2.3.0.jar /** * To read the uploaded csv file line by line * @param fileName : "fileName" as request.getFile('param name') * @return list */def readFile(fileName) { def list = [] fileName.inputStream.splitEachLine(','){ list << it } if (list.size() > 0) { return list } else { /*TODO add message : file is empty*/ return } } /** * Convert .xlsx file data to array * @param file as request.getFile('file as param name') * @return */def convertXlsxFileToArray(file) { def array = [] if(!file.empty) { XSSFWorkbook book = new XSSFWorkbook(file.getInputStream()); XSSFSheet[] sheets = book.sheets; for (XSSFSheet sheet : sheets) { sheet.each{row-> Iterator cellIterator = row.cellIterator() def record = [] while(cellIterator.hasNext()) { XSSFCell cell = cellIterator.next() record.add(cell) } array.add(record) } } } return array } /** * Convert .xlsx file data to array * @param file as request.getFile('file as param name') * @return */def convertXlsFileToArray(file) { def array = [] HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream()); HSSFSheet sheet = workbook.getSheetAt(0); sheet.each{row-> Iterator cellIterator = row.iterator() def record = [] while(cellIterator.hasNext()) { HSSFCell cell = cellIterator.next() record.add(cell) } array.add(record) } return array }

No comments:

Post a Comment