List of usage examples for org.apache.poi.ss.usermodel Row cellIterator
Iterator<Cell> cellIterator();
From source file:com.siacra.beans.GrupoBean.java
public void archivoXlsx(String path, FileUploadEvent archivo) { excelResponse = new ArrayList<>(); List<Horario> horas = new ArrayList<>(); try {// w w w. j av a 2 s .c o m FileInputStream file = new FileInputStream(new File(path + "\\" + archivo.getFile().getFileName())); // Crear el objeto que tendra el libro de Excel XSSFWorkbook workbook = new XSSFWorkbook(file); /* * Obtenemos la primera pestaa a la que se quiera procesar indicando el indice. * Una vez obtenida la hoja excel con las filas que se quieren leer obtenemos el iterator * que nos permite recorrer cada una de las filas que contiene. */ XSSFSheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); Row row; // Recorremos todas las filas para mostrar el contenido de cada celda int cantidad = 0; int cantidad2 = 0; while (rowIterator.hasNext()) { row = rowIterator.next(); if (cantidad2 != 0) { Horario h = new Horario(); UpploadGrupos grupo = new UpploadGrupos(); // Obtenemos el iterator que permite recorres todas las celdas de una fila Iterator<Cell> cellIterator = row.cellIterator(); Cell celda; cantidad = 1; while (cellIterator.hasNext()) { celda = cellIterator.next(); // if((cantidad%10)==0) // { // System.out.print(grupo.toString()); // excelResponse.add(grupo); // grupo = new UpploadGrupos(); // cantidad=1; // } // Dependiendo del formato de la celda el valor se debe mostrar como String, Fecha, boolean, entero... switch (celda.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(celda)) { SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss"); String fecha = f.format(celda.getDateCellValue()); System.out.print(":::::::: " + fecha); Date dos = f.parse(fecha); if (cantidad == 4) { h.setHinicio1(dos); grupo.setInicio1(dos); cantidad++; } else if (cantidad == 5) { h.setHfin1(dos); grupo.setFin1(dos); cantidad++; } else if (cantidad == 7) { h.setHinicio2(dos); grupo.setInicio2(dos); cantidad++; } else if (cantidad == 8) { h.setHfin2(dos); grupo.setFin2(dos); cantidad++; } System.out.println(dos); } // else // { // double numero = celda.getNumericCellValue(); // System.out.println(celda.getNumericCellValue()); // } break; case Cell.CELL_TYPE_STRING: if (cantidad == 1) { grupo.setAsignatura(celda.getStringCellValue()); cantidad++; } else if (cantidad == 2) { grupo.setTipoGrupo(celda.getStringCellValue()); cantidad++; } else if (cantidad == 3) { h.setDia1(celda.getStringCellValue()); grupo.setDia1(celda.getStringCellValue()); cantidad++; } else if (cantidad == 6) { h.setDia2(celda.getStringCellValue()); grupo.setDia2(celda.getStringCellValue()); cantidad++; } else if (cantidad == 9) { grupo.setNumeroGrupo(celda.getStringCellValue()); cantidad++; } else if (cantidad == 10) { grupo.setCupos(celda.getStringCellValue()); cantidad++; } String texto = celda.getStringCellValue(); System.out.println(celda.getStringCellValue()); break; // case Cell.CELL_TYPE_BOOLEAN: // System.out.println(celda.getBooleanCellValue()); // break; }//fin if que obtiene valor de celda } //fin while que recorre celdas System.out.print("objeto:::" + grupo.toString()); System.out.print("objeto:::" + h.toString()); horas.add(h); excelResponse.add(grupo); } // fin if primera iteracion cantidad2++; } // fin while que recorre filas // cerramos el libro excel workbook.close(); } catch (Exception e) { e.printStackTrace(); } procesarListaCargada(); }
From source file:com.testmax.util.ExcelSheet.java
License:CDDL license
/** * This method is used to read the data's from an excel file. * @param sheetIndex - Index of sheet 0,1,2 etc. * @param rowIndex - Index of row 0,1,2 etc. * *///from w w w . j a va 2s . co m private List<String> readExcelRow(int sheetIndex, int rowIndex) { String cellContents = ""; ArrayList<String> rowVal = new ArrayList<String>(); try { FileInputStream fileInputStream = new FileInputStream(this.fileName); POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream); HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem); HSSFSheet sheet = workBook.getSheetAt(sheetIndex); Row row = sheet.getRow(rowIndex); Iterator<Cell> colIt = row.cellIterator(); while (colIt.hasNext()) { Cell cell = colIt.next(); cellContents = cell.getStringCellValue(); rowVal.add(cellContents); } } catch (IOException e) { WmLog.printMessage("ERROR in reading Excel File=" + this.fileName + " Sheet Index=" + sheetIndex + " Excel Row Index=" + rowIndex + " " + e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); return null; } return (rowVal); }
From source file:com.testmax.util.ExcelSheet.java
License:CDDL license
/** * This method is used to read the data's from an excel file. * @param sheetIndex - Index of sheet 0,1,2 etc. * *///w ww.ja v a 2 s .c om private List<ArrayList> readExcel(int sheetIndex) { String cellContents = ""; ArrayList<ArrayList> excel = new ArrayList<ArrayList>(); ArrayList<String> rowVal = new ArrayList<String>(); try { FileInputStream fileInputStream = new FileInputStream(this.fileName); POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream); HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem); HSSFSheet sheet = workBook.getSheetAt(sheetIndex); Iterator<Row> rowIt = sheet.rowIterator(); while (rowIt.hasNext()) { Row row = rowIt.next(); Iterator<Cell> colIt = row.cellIterator(); while (colIt.hasNext()) { Cell cell = colIt.next(); cellContents = cell.getStringCellValue(); rowVal.add(cellContents); } excel.add(rowVal); } } catch (IOException e) { WmLog.printMessage("ERROR in reading Excel Sheet Index=" + sheetIndex + " Excel File=" + this.fileName + " " + e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); return null; } return (excel); }
From source file:com.tm.hiber.service.TMDataOperationServiceImpl.java
@Override public List<TaskMasterExcelTemplate> prepareTaskMasterFromExcel(File excelFile) { mLogger.log(Level.INFO, "prepareTaskMasterFromExcel--Starts"); if (excelFile != null && excelFile.exists()) { InputStream fis = null;/*from ww w . j av a2s. c om*/ try { mTaskMasterList.clear(); fis = new FileInputStream(excelFile); HSSFWorkbook objWorkBook = new HSSFWorkbook(fis); HSSFSheet objSheet = objWorkBook.getSheetAt(0); Iterator<Row> rowItr = objSheet.iterator(); TaskMasterExcelTemplate objTaskMaster; while (rowItr.hasNext()) { Row row = rowItr.next(); objTaskMaster = new TaskMasterExcelTemplate(); Iterator<Cell> cellItr = row.cellIterator(); while (cellItr.hasNext()) { Cell objCell = cellItr.next(); String cellValue = getCellData(objCell); switch (objCell.getColumnIndex()) { case 0: objTaskMaster.setTaskReference(cellValue); break; case 2: Date createDate = parseDate(cellValue); if (createDate != null) { objTaskMaster.setCreateDate(createDate); } break; case 6: objTaskMaster.setTitle(cellValue); break; case 7: objTaskMaster.setDescription(cellValue); break; case 8: objTaskMaster.setPriority(cellValue); break; case 18: objTaskMaster.setProjectName(cellValue); break; } } objTaskMaster.setAuditLastupdateon(new Date()); objTaskMaster.setAuditLastupdateby(UtilService.self().getSystemUser()); mTaskMasterList.add(objTaskMaster); } } catch (Exception ex) { mLogger.log(Level.FATAL, ex.getMessage()); } finally { try { if (fis != null) { fis.close(); } } catch (IOException ex) { mLogger.log(Level.FATAL, ex.getMessage()); } } } mLogger.log(Level.INFO, "prepareTaskMasterFromExcel--Ends"); return mTaskMasterList; }
From source file:com.tutorial.excelreadwrite.excelFunctions.java
public void convertColor(int r, int g, int b, int numColors) { //Get the userDefinedColor and set the style userDefinedColor = new XSSFColor(new java.awt.Color(r, g, b)); XSSFCellStyle userDefinedCS = workbook.createCellStyle(); userDefinedCS.setFillForegroundColor(userDefinedColor); userDefinedCS.setFillPattern(CellStyle.SOLID_FOREGROUND); //Create an arrayList and add foreground colors that will be converted and then remove them List<XSSFColor> listOfColors = new ArrayList(); for (int i = 0; i < numColors; ++i) { try { //First row of excel document will be reserved for obtaining the colors of the foreground used listOfColors.add(sheet.getRow(0).getCell(i).getCellStyle().getFillForegroundXSSFColor()); sheet.getRow(0).getCell(i).setCellStyle(null); } catch (NullPointerException ex) { throw new NullPointerException("Either incorrect # colors entered OR colors NOT SET."); }//from ww w . j a va2s .c o m } //Set-up rowIterator and get Row Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); //Set-up cellIterator and get Cell Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); //Null-Check for Cell if (cell != null) { //Get the Cell Style, Null-Check for Cell Style XSSFCellStyle currCellStyle = (XSSFCellStyle) cell.getCellStyle(); if (currCellStyle != null) { //Get the fillForeground color XSSFColor fgColor = currCellStyle.getFillForegroundXSSFColor(); //cycle through ArrayList and compare if any of the colors listed matches for (XSSFColor col : listOfColors) { if (col.equals(fgColor)) { cell.setCellStyle(userDefinedCS); } } } } } } }
From source file:com.tutorial.excelreadwrite.excelFunctions.java
public void markHorizontal(int spacesApart){ //Set-up rowIterator and get Row Iterator<Row> rowIterator = sheet.iterator(); while(rowIterator.hasNext()){ Row row = rowIterator.next(); //from w ww . j a v a 2s .c o m //Set-up cellIterator and get Cell Iterator<Cell> cellIterator = row.cellIterator(); while(cellIterator.hasNext()){ Cell cell = cellIterator.next(); //Obtains the Cell Style XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle(); //Checks to see if the Cell Style is null; if null, go to next cell if(cellStyle != null){ //Checks to see what color is the cell's color XSSFColor cellColor = cellStyle.getFillForegroundXSSFColor(); //Checks to see if color is null; if not compare to accept only editted or userDefined cells if(cellColor != null){ //Checks if current cell is userDefined or editted //If it is not, then go to the next cell if(cellColor.equals(mark.getFillForegroundXSSFColor()) || cellColor.equals(userDefinedColor)){ //Set boolean isCellMarked to false before proceeding isCellMarked = false; //Define Cell to be (spacesApart+1) away //So if x = current cell then the cell that is 5 spacesApart = // [x][][][][][][x] Cell cellMark = sheet.getRow(cell.getRowIndex()).getCell(cell.getColumnIndex() + spacesApart + 1); //Checks to see if cell is null; if present, get its Cell Style if(cellMark != null){ XSSFCellStyle cellMarkStyle = (XSSFCellStyle)cellMark.getCellStyle(); //Checks to see if the style is null; if present, get its color if(cellMarkStyle != null){ XSSFColor cellMarkColor = cellMarkStyle.getFillForegroundXSSFColor(); //Checks to see if the color is null; if present, compare colors if(cellMarkColor != null){ if(cellMarkColor.equals(userDefinedColor)){ isCellMarked = true; } } } } /* ** CHECK#1: 'isCellMarked' ** If isCellMarked is marked true, start iterating through the ** cells in between and check if null or not userDefinedStyle */ if(isCellMarked == true){ for(int i = 1; i <= spacesApart; ++i){ Cell isNull = sheet.getRow(cell.getRowIndex()).getCell(cell.getColumnIndex()+i); //Checks to see if the cell is null; if color is present, set isCellMarked to false if(isNull != null){ XSSFCellStyle cellCheckIfNullCellStyle = (XSSFCellStyle)isNull.getCellStyle(); if(cellCheckIfNullCellStyle != null){ XSSFColor cellCheckIfNullColor = cellCheckIfNullCellStyle.getFillForegroundXSSFColor(); if(cellCheckIfNullColor != null){ if(cellCheckIfNullColor.equals(userDefinedColor)){ isCellMarked = false; break; } } } } } } /* ** CHECK#2: 'isCellMarked2' ** If isCellMarked remains as true, set the two cell's style */ if(isCellMarked == true){ cell.setCellStyle(mark); cellMark.setCellStyle(mark); } } } } } } }
From source file:com.ucuenca.dao.BaseExcelDao.java
/** * This method gets columns//from w ww. j a v a 2 s . com * * @param sheet * @Author pablo and adrian * @return list cols */ public List<Column> getColumn(Sheet sheet) { Iterator<Row> rowIterator = sheet.iterator(); List<Column> columns = new ArrayList<Column>(); while (rowIterator.hasNext()) { Column colum = new Column_Excel(); Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); if (Cell.CELL_TYPE_STRING == cell.getCellType()) { colum.setTitle(cell.getStringCellValue()); } else if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { colum.setTitle(cell.getStringCellValue()); } } columns.add(colum); } return columns; }
From source file:com.unicomer.oer.harvester.reader.ExcelBrokerRemoteReader.java
public List<Set<Entity>> read() throws Exception { List<Set<Entity>> list = new ArrayList<Set<Entity>>(); HashMap<String, Entity> servicesMap = new HashMap<String, Entity>(); String defEnvironment = prop.getProperty("default.environment"); String defaultAssetType = prop.getProperty("broker.service.asset-type"); String resourceEnvironmentXPath = prop.getProperty("broker.custom-data.environment"); String resourceNameXPath = prop.getProperty("broker.custom-data.endpoint"); // String defServiceToAppRelation = prop.getProperty("broker.service-to-app-relation"); String harvestType = prop.getProperty("broker.harvest-type"); String transportProtocolXpath = prop.getProperty("broker.custom-data.transport-protocol"); String authenticationMethod = prop.getProperty("broker.custom-data.authentication"); String authorizationMethod = prop.getProperty("broker.custom-data.authentication"); boolean hasHeader = Boolean.valueOf(prop.getProperty("broker.has-header")); try {/*w ww.java 2 s .c o m*/ FileInputStream file = new FileInputStream(new File(templateFile)); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); if (hasHeader) { hasHeader = false; } else { Iterator<Cell> cellIterator = row.cellIterator(); String name = cellIterator.next().getStringCellValue(); String description = cellIterator.next().getStringCellValue(); String originProtocol = cellIterator.next().getStringCellValue(); String resourceName = cellIterator.next().getStringCellValue(); // String location = cellIterator.next().getStringCellValue(); // String originSystem = cellIterator.next().getStringCellValue(); // String targetProtocol = cellIterator.next().getStringCellValue(); // String targetSystem = cellIterator.next().getStringCellValue(); String version = getVersion(name); logger.info("Asset: " + name + " - " + version); UnicomerEntity entity = new UnicomerEntity(defaultAssetType, name, name, description, version, ArtifactAlgorithm.DEFAULT); entity.addCategorization("LineOfBusiness", prop.getProperty("broker.line-of-business")); entity.addCategorization("AssetLifecycleStage", prop.getProperty("default.asset-lifecycle-stage")); entity.addCategorization("Technology", prop.getProperty("broker.technology")); entity.addCategorization("Region", prop.getProperty("default.region")); entity.addHarvesterProperty("Modulo", harvestType); entity.addHarvesterProperty("Harvester Description", prop.getProperty("default.harvester-description")); entity.addCustomData("acquisition-method", prop.getProperty("default.acquisition-method")); entity.addCustomData(resourceEnvironmentXPath, defEnvironment); entity.addCustomData(resourceNameXPath, resourceName); entity.addCustomData(transportProtocolXpath, originProtocol); entity.addCustomData("authentication-method", authenticationMethod); entity.addCustomData("authorization-method", authorizationMethod); entity.addCustomData("has-test-scripts", "true"); entity.addCustomData("needs-performance-testing", "false"); entity.addCustomData("has-automated-testing", "false"); entity.addCustomData("consistent-with-business-mission", "true"); entity.addCustomData("passes-legal-review", "true"); entity.addCustomData("approved-for-internal-use", "true"); entity.addCustomData("approved-for-external-use", "false"); entity.addCustomData("passes-technical-review", "true"); entity.addCustomData("downtime-impact", prop.getProperty("broker.downtime-impact")); entity.addCustomData("license-terms", prop.getProperty("broker.license-terms")); servicesMap.put(name, entity); } } workbook.close(); file.close(); list.add(new HashSet<Entity>(servicesMap.values())); for (Set<Entity> entitySet : list) { if (entitySet != null && entitySet.size() > 0) { YamlWriter.writeToYaml(entitySet, harvestType); } } } catch (Exception e) { e.printStackTrace(); } return list; }
From source file:com.vaadin.addon.spreadsheet.CellValueManager.java
License:Open Source License
/** * Method for updating cells that are marked for update and formula cells. * * Iterates over the whole sheet (existing rows and columns) and updates * client side cache for all sent formula cells, and cells that have been * marked for updating.//from w w w . jav a 2 s .c o m * */ protected void updateMarkedCellValues() { final ArrayList<CellData> updatedCellData = new ArrayList<CellData>(); Sheet sheet = spreadsheet.getActiveSheet(); // it is unnecessary to worry about having custom components in the cell // because the client side handles it -> it will not replace a custom // component with a cell value // update all cached formula cell values on client side, because they // might have changed. also make sure all marked cells are updated Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { final Row r = rows.next(); final Iterator<Cell> cells = r.cellIterator(); while (cells.hasNext()) { final Cell cell = cells.next(); int rowIndex = cell.getRowIndex(); int columnIndex = cell.getColumnIndex(); final String key = SpreadsheetUtil.toKey(columnIndex + 1, rowIndex + 1); CellData cd = createCellDataForCell(cell); // update formula cells if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { if (cd != null) { if (sentFormulaCells.contains(key) || markedCells.contains(key)) { sentFormulaCells.add(key); updatedCellData.add(cd); } } else if (sentFormulaCells.contains(key)) { // in case the formula cell value has changed to null or // empty; this case is probably quite rare, formula cell // pointing to a cell that was removed or had its value // cleared ??? sentFormulaCells.add(key); cd = new CellData(); cd.col = columnIndex + 1; cd.row = rowIndex + 1; cd.cellStyle = "" + cell.getCellStyle().getIndex(); updatedCellData.add(cd); } } else if (markedCells.contains(key)) { sentCells.add(key); updatedCellData.add(cd); } } } if (!changedFormulaCells.isEmpty()) { fireFormulaValueChangeEvent(changedFormulaCells); changedFormulaCells = new HashSet<CellReference>(); } // empty cells have cell data with just col and row updatedCellData.addAll(removedCells); if (!updatedCellData.isEmpty()) { spreadsheet.getRpcProxy().cellsUpdated(updatedCellData); spreadsheet.getRpcProxy().refreshCellStyles(); } markedCells.clear(); removedCells.clear(); }
From source file:com.validation.manager.core.tool.table.extractor.TableExtractor.java
License:Apache License
public List<DefaultTableModel> extractTables() throws IOException, FileNotFoundException, ClassNotFoundException, VMException { List<DefaultTableModel> tables = new ArrayList<>(); if (source.getName().endsWith(".doc") || source.getName().endsWith(".docx") || source.getName().endsWith(".docm")) { //Word documents tables = loadSerializedTables(); } else if (source.getName().endsWith(".xls")) { //Pre Office 2007+ XML //Excel documents FileInputStream file = new FileInputStream(source); //Get the workbook instance for XLS file HSSFWorkbook workbook = new HSSFWorkbook(file); //Get first sheet from the workbook Sheet sheet = workbook.getSheetAt(0); //Get iterator to all the rows in current sheet Iterator<Row> rowIterator = sheet.iterator(); int rowNum = 0; int columns = 0; Map<Integer, ArrayList<Object>> data = new HashMap<>(); while (rowIterator.hasNext()) { ArrayList<Object> cells = new ArrayList<>(); Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); cells.add(cell.getStringCellValue().trim()); if (rowNum == 0) { columns++;/*ww w. ja v a2s .c o m*/ } } data.put(rowNum, cells); rowNum++; } //Process Object[][] data2 = new Object[rowNum][columns]; String[] title = new String[columns]; for (int i = 0; i < columns; i++) { title[i] = format("Column {0}", i + 1); } int row = 0; int col = 0; for (int i = 0; i < rowNum; i++) { for (Object obj : data.get(row)) { LOG.log(Level.FINE, "r: {0} c: {1} v: {2}", new Object[] { row, col, obj }); data2[row][col] = obj; col++; } row++; col = 0; } tables.add(new DefaultTableModel(data2, title)); } else if (source.getName().endsWith(".xlsx") || source.getName().endsWith(".xlsm")) { //Office 2007+ XML FileInputStream file = new FileInputStream(source); //Get the workbook instance for XLS file XSSFWorkbook workbook = new XSSFWorkbook(file); //Get first sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); //Get iterator to all the rows in current sheet Iterator<Row> rowIterator = sheet.iterator(); int rowNum = 0; int columns = 0; Map<Integer, ArrayList<Object>> data = new HashMap<>(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); ArrayList<Object> cells = new ArrayList<>(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); cells.add(cell.getStringCellValue().trim()); if (rowNum == 0) { columns++; } } data.put(rowNum, cells); rowNum++; } //Process Object[][] data2 = new Object[rowNum][columns]; String[] title = new String[columns]; for (int i = 0; i < columns; i++) { title[i] = format("Column {0}", i + 1); } int row = 0, col = 0; for (int i = 0; i < rowNum; i++) { for (Object obj : data.get(row)) { LOG.log(Level.FINE, "r: {0} c: {1} v: {2}", new Object[] { row, col, obj }); data2[row][col] = obj; col++; } row++; col = 0; } tables.add(new DefaultTableModel(data2, title)); } else { throw new VMException(format("Invalid import file: {0}", source)); } return tables; }