List of usage examples for org.apache.poi.ss.usermodel Cell getStringCellValue
String getStringCellValue();
For numeric cells we throw an exception.
From source file:com.epitech.oliver_f.astextexls.ReadXLSFiles.java
private List<ResultRow> parseAllFiles(List<Path> paths) { List<ResultRow> resultList = new ArrayList<ResultRow>(); for (Path path : paths) { try {//from w w w . ja v a2s . c o m System.out.println("file : " + path.toAbsolutePath()); FileInputStream file = new FileInputStream(path.toFile()); Workbook wb = WorkbookFactory.create(file); Sheet sheet = wb.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); boolean found = false; while (rowIterator.hasNext()) { Row row = rowIterator.next(); //For each row, iterate through all the columns Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); //Check the cell type and format accordingly String res = null; if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { double inte = cell.getNumericCellValue(); res = Double.toString(inte); } if (cell.getCellType() == Cell.CELL_TYPE_STRING) { res = cell.getStringCellValue(); } if (res != null && res.trim().toLowerCase().equals("login \nvaluateur")) { found = true; } } if (found) { System.out.println("found ! "); ResultRow rr = new ResultRow(); Row rowFound = rowIterator.next(); Iterator<Cell> c = rowFound.cellIterator(); while (c.hasNext()) { Cell cel = c.next(); String res = null; if (cel.getCellType() == Cell.CELL_TYPE_NUMERIC) { double inte = cel.getNumericCellValue(); res = Double.toString(inte); } if (cel.getCellType() == Cell.CELL_TYPE_STRING) { res = cel.getStringCellValue(); } rr.result.add(res); } resultList.add(rr); found = false; break; } } file.close(); } catch (IOException | InvalidFormatException e) { e.printStackTrace(); } } return resultList; }
From source file:com.Excel.Excel.java
private void leerArchivo(int indiceHoja) { abrirArchivo();/*from w w w. ja v a2 s .com*/ this.datos = new HashMap<>(); HSSFSheet sheet = workbook.getSheetAt(indiceHoja); Iterator<Row> rowIterator = sheet.iterator(); int fila = 0; Row row; while (rowIterator.hasNext()) { List<Object> datosFila = new ArrayList<>(); Cell celda; row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Object dato = null; celda = cellIterator.next(); switch (celda.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(celda)) { System.out.print(celda.getDateCellValue()); dato = celda.getDateCellValue(); } else { System.out.print(celda.getNumericCellValue()); dato = celda.getNumericCellValue(); } break; case Cell.CELL_TYPE_STRING: System.out.print(celda.getStringCellValue()); dato = celda.getStringCellValue(); break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(celda.getBooleanCellValue()); dato = celda.getBooleanCellValue(); break; } datosFila.add(dato); } datos.put(fila++, datosFila); System.out.println(""); } cerrarArchivo(); }
From source file:com.Excel.Excel2007.java
private void leerArchivo(int indiceHoja) { abrirArchivo();//from ww w .j a va 2 s . c o m this.datos = new HashMap<>(); XSSFSheet sheet = workbook.getSheetAt(indiceHoja); Iterator<Row> rowIterator = sheet.iterator(); int fila = 0; Row row; while (rowIterator.hasNext()) { List<Object> datosFila = new ArrayList<>(); Cell celda; row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Object dato = null; celda = cellIterator.next(); switch (celda.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(celda)) { System.out.print(celda.getDateCellValue()); dato = celda.getDateCellValue(); } else { System.out.print(celda.getNumericCellValue()); dato = celda.getNumericCellValue(); } break; case Cell.CELL_TYPE_STRING: System.out.print(celda.getStringCellValue()); dato = celda.getStringCellValue(); break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(celda.getBooleanCellValue()); dato = celda.getBooleanCellValue(); break; } datosFila.add(dato); } datos.put(fila++, datosFila); System.out.println(""); } cerrarArchivo(); }
From source file:com.exilant.exility.core.XLSReader.java
License:Open Source License
/** * Purpose of this method to read rows from given Excel Sheet. * //from w w w.ja va 2 s.c o m * @param sheet * an Instance of .ss.usermodel.Sheet class from POI apache. * @return -1 if fail to read sheet else number of columns read successfully * from the sheet. * @throws ExilityException */ public int readASheet(Sheet sheet) throws ExilityException { int nonEmptyFirstRowIdx = 0; int lastRowIdx = 0; int nbrPhysicalRows = sheet.getPhysicalNumberOfRows(); String sheetName = sheet.getSheetName(); if (nbrPhysicalRows < 2) { Spit.out(sheetName + XLSReader.INSUFFICIENT_DATA_ROWS); return -1; } try { nonEmptyFirstRowIdx = sheet.getFirstRowNum(); lastRowIdx = sheet.getLastRowNum(); /* * For checking to valid header.First row must be header. */ Row headerRow = sheet.getRow(nonEmptyFirstRowIdx); int nbrCol = headerRow.getPhysicalNumberOfCells(); for (int colIdx = 0; colIdx < nbrCol; colIdx++) { Cell hCell = headerRow.getCell(colIdx); if (hCell == null || hCell.getCellType() == Cell.CELL_TYPE_BLANK) { Spit.out("Error--->Found blank column " + (colIdx + 1) + " in Sheet " + sheetName + XLSReader.INVALID_HEADER); this.columnsData.clear(); return -1; } String columnName = hCell.getStringCellValue(); this.setDataType(columnName, colIdx); } } catch (Exception e) { Spit.out(sheetName + XLSReader.INVALID_HEADER); Spit.out(e); return -1; } int nbrColumnsInARow = this.columnsData.size(); /* * Loop starts with second data row that is first row(header as column * name) excluded. */ Spit.out(sheetName + ":\n"); for (int rowIdx = (nonEmptyFirstRowIdx + 1); rowIdx <= lastRowIdx; rowIdx++) { Row row = sheet.getRow(rowIdx); if (row == null) { Spit.out(XLSReader.SKIP_BLANK_ROW + rowIdx); continue; } /** * readARow() will throws ExilityException if something goes wrong. */ this.readARow(row, nbrColumnsInARow); } return this.columnsData.size(); }
From source file:com.exilant.exility.core.XLSReader.java
License:Open Source License
/** * purpose of this method to create ValueList along with types and column * name. Simple design followed : Just have ColumnMetaData object which * contains everything. For a Cell we will have one columnMetaData object * and it will have values across the//www . ja v a 2 s.c om * * @param row * @throws Exception */ private void readARow(Row row, int nbrColumnsInARow) throws ExilityException { Value[] columnValues = new Value[nbrColumnsInARow]; Value aColumnValue = null; String rawValue = null; for (int c = 0; c < nbrColumnsInARow; c++) { Cell cell = row.getCell(c, Row.CREATE_NULL_AS_BLANK); ColumnMetaData columnInfo = this.columnsData.get(new Integer(c)); int xlsColumnDataType = columnInfo.getXlsDataType(); DataValueType exilDataType = null; int cellType = cell.getCellType(); if (xlsColumnDataType != XLSReader.UNKNOWN_TYPE) { cellType = xlsColumnDataType; } try { switch (cellType) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { rawValue = DateUtility.formatDate(cell.getDateCellValue()); /* * returns yyyy-mm-dd hh:mm:ss.sss full date with time. */ exilDataType = DataValueType.DATE; } else { double decimalNumber = cell.getNumericCellValue(); rawValue = NumberToTextConverter.toText(decimalNumber); boolean isDecimal = rawValue.contains("."); if (isDecimal) { exilDataType = DataValueType.DECIMAL; } else { exilDataType = DataValueType.INTEGRAL; } } break; case Cell.CELL_TYPE_STRING: rawValue = cell.getStringCellValue().trim(); exilDataType = DataValueType.TEXT; break; case Cell.CELL_TYPE_FORMULA: rawValue = cell.getStringCellValue().trim(); exilDataType = DataValueType.TEXT; break; case Cell.CELL_TYPE_BLANK: rawValue = cell.getStringCellValue(); exilDataType = DataValueType.NULL; columnInfo.setExilDataType(exilDataType); break; case Cell.CELL_TYPE_BOOLEAN: rawValue = cell.getBooleanCellValue() ? BooleanValue.TRUE : BooleanValue.FALSE; exilDataType = DataValueType.BOOLEAN; break; default: String msg = columnInfo.getColumnName() + XLSReader.INVALID_COLUMN_TYPE + row.getRowNum(); Spit.out(msg); } } catch (Exception e) { // Trying to set valueType value and expected valueType value // for column in row String[] params = { this.getXlsTypeAsText(cell.getCellType()), this.getXlsTypeAsText(cellType), columnInfo.getColumnName(), "" + row.getRowNum() }; String message = this.replaceMessageParams(XLSReader.DATATYPE_MISMATCH, params); throw new ExilityException(message); } if (xlsColumnDataType == XLSReader.UNKNOWN_TYPE && cellType != Cell.CELL_TYPE_BLANK) { columnInfo.setXlsDataType(cellType); columnInfo.setExilDataType(exilDataType); } exilDataType = columnInfo.getExilDataType(); aColumnValue = Value.newValue(rawValue, exilDataType); columnValues[c] = aColumnValue; this.columnsData.put(new Integer(c), columnInfo); } this.rows.add(columnValues); }
From source file:com.exilant.exility.core.XlxUtil.java
License:Open Source License
/*** * get text value of cell irrespective of its content type * //from w w w . j av a2 s.co m * @param cell * @return */ private String getTextValue(Cell cell) { if (cell == null) { return EMPTY_STRING; } int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_BLANK) { return EMPTY_STRING; } if (cellType == Cell.CELL_TYPE_FORMULA) { cellType = cell.getCachedFormulaResultType(); } if (cellType == Cell.CELL_TYPE_STRING) { return cell.getStringCellValue().trim(); } /* * dates are internally stored as decimal.. */ if (cellType == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { return DateUtility.formatDate(cell.getDateCellValue()); } return NumberFormat.getInstance().format(cell.getNumericCellValue()); } if (cellType == Cell.CELL_TYPE_BOOLEAN) { if (cell.getBooleanCellValue()) { return "1"; } return "0"; } return EMPTY_STRING; }
From source file:com.exilant.exility.core.XlxUtil.java
License:Open Source License
private void addMissingRows(Sheet sheet, String[][] rows) { /**//from w w w .j a v a 2 s . c o m * create a set of existing labels */ Set<String> existingEntries = new HashSet<String>(); int lastRow = sheet.getLastRowNum(); for (int i = 0; i <= lastRow; i++) { Row row = sheet.getRow(i); if (row == null) { continue; } Cell cell = row.getCell(0); if (cell == null) { continue; } existingEntries.add(cell.getStringCellValue()); } /** * now, add rows, only if they are not there already */ for (String[] row : rows) { if (existingEntries.contains(row[0])) { continue; } lastRow++; Row xlRow = sheet.createRow(lastRow); int colIdx = 0; for (String columnValue : row) { xlRow.createCell(colIdx).setCellValue(columnValue); colIdx++; } } }
From source file:com.fanniemae.ezpie.data.connectors.ExcelConnector.java
License:Open Source License
protected void readColumnNames() { // read the schema from the first row or the named row. _headerRange = null;/*ww w. java 2s .co m*/ Row headerRow = null; if (StringUtilities.isNotNullOrEmpty(_columnNameAddress)) { _headerRange = new ExcelRange(_columnNameAddress); CellReference cr = _headerRange.getStartCell(); headerRow = _sheet.getRow(cr.getRow()); } else { Iterator<Row> iterator = _sheet.iterator(); headerRow = iterator.next(); } _columnCount = 0; int endColumnIndex = (_headerRange == null) ? -1 : _headerRange.getEndColumn(); String value = ""; _columnLabels = new ArrayList<String>(); _columnAddress = new ArrayList<String>(); List<String> usedLabels = new ArrayList<String>(); for (Cell cell : headerRow) { String columnLetter = CellReference.convertNumToColString(cell.getColumnIndex()); if ((endColumnIndex != -1) && (cell.getColumnIndex() > endColumnIndex)) { break; } CellType ct = cell.getCellTypeEnum(); if (ct == CellType.FORMULA) ct = cell.getCachedFormulaResultTypeEnum(); switch (ct) { case STRING: value = cell.getStringCellValue(); if (usedLabels.contains(value.toLowerCase())) value = String.format("%s_%s%d", value, columnLetter, cell.getRowIndex() + 1); else usedLabels.add(value.toLowerCase()); _columnLabels.add(value); _columnAddress.add(columnLetter); break; case BOOLEAN: case NUMERIC: case FORMULA: case BLANK: _columnLabels.add(String.format("Column_%s", columnLetter)); _columnAddress.add(columnLetter); break; default: break; } } _columnCount = _columnLabels.size(); _dataSchema = new String[_columnCount][2]; _dataTypes = new DataType[_columnCount]; for (int i = 0; i < _columnCount; i++) { _dataSchema[i][0] = _columnLabels.get(i); } }
From source file:com.fanniemae.ezpie.data.connectors.ExcelConnector.java
License:Open Source License
protected Object[] readExcelData(Row excelDataRow) { Object[] data = new Object[_columnCount]; String cellAddress = ""; int dataIndex = 0; try {/*from w w w . j a v a2 s . c o m*/ for (Cell cell : excelDataRow) { cellAddress = cell.getAddress().toString(); String columnLetter = CellReference.convertNumToColString(cell.getColumnIndex()); int columnIndex = _columnAddress.indexOf(columnLetter); if (columnIndex == -1) { continue; } CellType ct = cell.getCellTypeEnum(); if (ct == CellType.FORMULA) ct = cell.getCachedFormulaResultTypeEnum(); switch (ct) { case STRING: data[dataIndex] = cell.getStringCellValue(); break; case BOOLEAN: data[dataIndex] = _allTypesStrings ? Boolean.toString(cell.getBooleanCellValue()) : cell.getBooleanCellValue(); break; case NUMERIC: data[dataIndex] = _allTypesStrings ? Double.toString(cell.getNumericCellValue()) : cell.getNumericCellValue(); break; default: data[dataIndex] = _allTypesStrings ? "" : null; break; } dataIndex++; } if (_addFilename) data[data.length - 1] = _filenameOnly; } catch (Exception ex) { throw new PieException( String.format("Error while reading Excel data from cell %s. %s", cellAddress, ex.getMessage()), ex); } return data; }
From source file:com.femsa.kof.csi.util.XlsAnalizer.java
/** * Mtodo encargado de la lectura y anlisis de una hoja del archivo excel * cargado en la interfaz grfica correspondiente a Rolling * * * @param rowIterator lista de renglones contenidos en la hoja de excel * @param usuario usuario que realiza el anlisis * @param sheetName nombre de la hoja de excel * @return Regresa una lista con los registros a ser almacenados en base de * datos//w ww .j a va 2 s . com */ private List<Xtmpinddl> analizeSheetIndi(Iterator<Row> rowIterator, DcsUsuario usuario, String sheetName, List<DcsCatPais> paises, List<DcsCatIndicadores> indicadores) throws DCSException { int numRow = 0; List<Xtmpinddl> cargas = new ArrayList<Xtmpinddl>(); Xtmpinddl indi; SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar calendarioActual = Calendar.getInstance(); Calendar calendario = Calendar.getInstance(); end: while (rowIterator != null && rowIterator.hasNext()) { Row row = rowIterator.next(); Cell cell; if (numRow == 0) { } else { indi = new Xtmpinddl(); cell = row.getCell(0); if (cell != null && cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { calendario.setTime(cell.getDateCellValue()); if ("User".equalsIgnoreCase(usuario.getFkIdRol().getRol()) && (calendarioActual.get(Calendar.YEAR) != calendario.get(Calendar.YEAR) || calendarioActual.get(Calendar.MONTH) != calendario.get(Calendar.MONTH))) { throw new DCSException( "Error: You can not load information of a different month of the current"); } indi.setFecha(sdf.format(cell.getDateCellValue())); } else if (cell != null && cell.getCellType() == Cell.CELL_TYPE_STRING) { try { calendario.setTime(sdf.parse(cell.getStringCellValue().trim())); if ("User".equalsIgnoreCase(usuario.getFkIdRol().getRol()) && (calendarioActual .get(Calendar.YEAR) != calendario.get(Calendar.YEAR) || calendarioActual.get(Calendar.MONTH) != calendario.get(Calendar.MONTH))) { throw new DCSException( "Error: You can not load information of a different month of the current"); } indi.setFecha(cell.getStringCellValue().trim()); } catch (ParseException ex) { Logger.getLogger(XlsAnalizer.class.getName()).log(Level.SEVERE, null, ex); errors.add("Approximately " + Character.toString((char) (65 + 0)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } } else { numRow++; continue; } cell = row.getCell(1); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_STRING) { indi.setGrupoInd(cell != null ? cell.getStringCellValue().trim() : null); } else { errors.add("Approximately " + Character.toString((char) (65 + 1)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(2); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_STRING) { if (indicadores.contains( new DcsCatIndicadores(cell != null ? cell.getStringCellValue().trim() : null))) { indi.setIndicador(cell != null ? cell.getStringCellValue().trim() : null); } else { errors.add("Approximately " + Character.toString((char) (65 + 2)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "], indicator not found."); cargas.clear(); break; } } else { errors.add("Approximately " + Character.toString((char) (65 + 2)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(3); if (cell != null && cell.getCellType() == Cell.CELL_TYPE_STRING) { if ("KOF".equalsIgnoreCase(cell.getStringCellValue().trim()) || paises.contains(new DcsCatPais(cell.getStringCellValue().trim()))) { indi.setPais(cell.getStringCellValue().trim()); } else { errors.add("Approximately " + Character.toString((char) (65 + 3)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } if ("User".equalsIgnoreCase(usuario.getFkIdRol().getRol()) && (!usuario.getPais().equalsIgnoreCase(indi.getPais()))) { throw new DCSException("Error: you can not load information from other country"); } } else { errors.add("Approximately " + Character.toString((char) (65 + 3)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(4); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_STRING || cell.getCellType() == Cell.CELL_TYPE_BLANK) { indi.setCentro(cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK ? cell.getStringCellValue().trim() : null); } else { errors.add("Approximately " + Character.toString((char) (65 + 4)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(5); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_STRING || cell.getCellType() == Cell.CELL_TYPE_BLANK) { indi.setRuta(cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK ? cell.getStringCellValue().trim() : null); } else { errors.add("Approximately " + Character.toString((char) (65 + 5)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(6); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { indi.setValorMensual(cell != null ? (float) cell.getNumericCellValue() : 0); } else { errors.add("Approximately " + Character.toString((char) (65 + 6)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cell = row.getCell(7); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { indi.setValorAcumulado(cell != null ? (float) cell.getNumericCellValue() : 0); } else { errors.add("Approximately " + Character.toString((char) (65 + 7)) + "" + (numRow + 1) + " cell in " + sheetName + " sheet have a invalid value [" + cell + "]."); cargas.clear(); break; } cargas.add(indi); } numRow++; } return cargas; }