Created
July 24, 2018 11:50
-
-
Save Ikhiloya/8ccabdedc02e46f5d5543ebf3b6266e8 to your computer and use it in GitHub Desktop.
Code Snippet to read from an excel file using Apache POI library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private ArrayList<String[]> readXcelDocuments(InputStream file) throws Exception { | |
| ArrayList<String[]> trans = new ArrayList<String[]>(); | |
| Workbook workbook = WorkbookFactory.create(file); | |
| FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); | |
| //Get first sheet from the workbook | |
| Sheet sheet = workbook.getSheetAt(0); | |
| for (int rowIndex = 1; rowIndex < sheet.getLastRowNum(); rowIndex++) { | |
| Row row = sheet.getRow(rowIndex); | |
| //creates a string array with the length of the last cell number | |
| String[] tran = new String[row.getLastCellNum()]; | |
| for (int colIndex = 0; colIndex < row.getLastCellNum(); colIndex++) { | |
| Cell cell = row.getCell(colIndex); | |
| CellValue cellValue = evaluator.evaluate(cell); | |
| if (cellValue == null) { | |
| tran[colIndex] = ""; | |
| continue; | |
| } | |
| switch (cellValue.getCellTypeEnum()) { | |
| case NUMERIC: | |
| tran[colIndex] = String.valueOf(cell.getNumericCellValue()); | |
| break; | |
| case STRING: | |
| tran[colIndex] = cell.getStringCellValue(); | |
| break; | |
| case BLANK: | |
| tran[colIndex] = ""; | |
| default: | |
| throw new Exception("Error in Document at Row " + (rowIndex + 1 + ", Column " + (colIndex + 1))); | |
| } | |
| } | |
| if (tran[0].trim().isEmpty()) | |
| break; | |
| trans.add(tran); | |
| } | |
| return trans; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment