Example usage for org.apache.poi.ss.usermodel Row cellIterator

List of usage examples for org.apache.poi.ss.usermodel Row cellIterator

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Row cellIterator.

Prototype

Iterator<Cell> cellIterator();

Source Link

Usage

From source file:de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelExportServiceImplTest.java

License:Open Source License

/**
 * @param wb the Workbook to be scanned/*w  w  w.ja  v a  2 s. c  o  m*/
 * @param expctContent the string we search for
 * 
 * @return true if one of the workbook's contains the searched string, false otherwise
 */
private boolean wbContainsString(ExportWorkbook wb, String expctContent) {

    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);

        for (Iterator<Row> rIt = sheet.rowIterator(); rIt.hasNext();) {
            Row r = rIt.next();

            for (Iterator<Cell> cIt = r.cellIterator(); cIt.hasNext();) {
                Cell c = cIt.next();
                try {
                    if (c.getStringCellValue().equals(expctContent)) {
                        return true;
                    }

                } catch (IllegalStateException e) {
                    // if numeric cells are encountered
                }
            }
        }
    }
    return false;
}

From source file:de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelExportServiceImplTest.java

License:Open Source License

/**
 * Method to print a workbook's cells-content. Handy if some errors show up.
 *//* w  w  w  .j  a v a  2 s  .  c o m*/
@SuppressWarnings("unused")
private void printWb(ExportWorkbook wb) {
    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);

        for (Iterator<Row> rIt = sheet.rowIterator(); rIt.hasNext();) {
            Row r = rIt.next();

            for (Iterator<Cell> cIt = r.cellIterator(); cIt.hasNext();) {
                Cell c = cIt.next();
                LOGGER.debug(c.toString());
            }
        }
    }
}

From source file:de.ks.idnadrev.expimp.xls.XlsxExporterTest.java

License:Apache License

@Test
public void testExportThoughts() throws Exception {
    File tempFile = File.createTempFile("thoughtExport", ".xlsx");
    EntityExportSource<Thought> source = new EntityExportSource<>(getAllIds(), Thought.class);
    XlsxExporter exporter = new XlsxExporter();
    exporter.export(tempFile, source);/*from  w w w.ja v  a  2  s .  co  m*/

    Workbook wb = WorkbookFactory.create(tempFile);
    Sheet sheet = wb.getSheetAt(0);
    assertEquals(Thought.class.getName(), sheet.getSheetName());
    int lastRowNum = sheet.getLastRowNum();
    assertEquals(COUNT, lastRowNum);
    Row firstRow = sheet.getRow(0);

    ArrayList<String> titles = new ArrayList<>();
    firstRow.cellIterator().forEachRemaining(col -> titles.add(col.getStringCellValue()));
    assertThat(titles.size(), greaterThanOrEqualTo(3));
    log.info("Found titles {}", titles);

    String creationTime = PropertyPath.property(Thought.class, t -> t.getCreationTime());
    String name = PropertyPath.property(Thought.class, t -> t.getName());
    String description = PropertyPath.property(Thought.class, t -> t.getDescription());

    assertTrue(titles.contains(creationTime));
    assertTrue(titles.contains(name));
    assertTrue(titles.contains(description));

    int nameColumn = titles.indexOf(name);
    ArrayList<String> names = new ArrayList<String>(COUNT);
    for (int i = 1; i <= COUNT; i++) {
        Row row = sheet.getRow(i);
        names.add(row.getCell(nameColumn).getStringCellValue());
    }
    Collections.sort(names);
    assertEquals("Thought000", names.get(0));
    assertEquals("Thought141", names.get(COUNT - 1));

    Date excelDate = sheet.getRow(1).getCell(titles.indexOf(creationTime)).getDateCellValue();

    Thought thought = PersistentWork.forName(Thought.class, "Thought000");

    Timestamp timestamp = java.sql.Timestamp.valueOf(thought.getCreationTime());
    Date creationDate = new Date(timestamp.getTime());
    assertEquals(creationDate, excelDate);
}

From source file:de.ks.idnadrev.expimp.xls.XlsxExporterTest.java

License:Apache License

@Test
public void testExportToManyRelation() throws Exception {
    File tempFile = File.createTempFile("taskExportTest", ".xlsx");
    EntityExportSource<Task> tasks = new EntityExportSource<>(PersistentWork.idsFrom(Task.class), Task.class);
    EntityExportSource<Tag> tags = new EntityExportSource<>(PersistentWork.idsFrom(Tag.class), Tag.class);
    XlsxExporter exporter = new XlsxExporter();
    exporter.export(tempFile, tasks, tags);

    Workbook wb = WorkbookFactory.create(tempFile);
    Sheet taskSheet = wb.getSheet(Task.class.getName());
    Sheet tagSheet = wb.getSheet(Tag.class.getName());
    assertNotNull(taskSheet);//  w w  w  . j a  v  a  2  s  .  c om
    assertNotNull(tagSheet);

    Row firstRow = taskSheet.getRow(0);
    int pos = 0;
    Iterator<Cell> cellIterator = firstRow.cellIterator();

    String property = PropertyPath.property(Task.class, t -> t.getTags());
    while (cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        if (cell.getStringCellValue().equals(property)) {
            break;
        }
        pos++;
    }
    assertNotEquals(Task.class.getSimpleName() + "." + property + " not exported", firstRow.getLastCellNum(),
            pos);

    Cell cell = taskSheet.getRow(1).getCell(pos);
    String[] split = StringUtils.split(cell.getStringCellValue(), ToManyColumn.SEPARATOR);
    assertEquals(2, split.length);
    assertTrue(Arrays.asList(split).contains("tag" + ToManyColumn.SEPARATOR_REPLACEMENT + "1"));
    assertTrue(Arrays.asList(split).contains("tag2"));
}

From source file:de.quamoco.qm.editor.export.ResultCalibrationImporter.java

License:Apache License

/** Calibrate the {@link MeasureEvaluation}s. */
private void importMeasureEvaluationCalibration(Sheet sheet, IProgressMonitor monitor) {
    Row row = sheet.getRow(5);
    for (Iterator<Cell> i = row.cellIterator(); i.hasNext();) {
        Cell cell = i.next();/*from ww  w. j  av  a2  s .  com*/
        int column = cell.getColumnIndex();
        if (column < 1) {
            continue;
        }
        String id = cell.getStringCellValue();
        EObject evaluation = getEvaluation(id);
        if (evaluation instanceof SingleMeasureEvaluation) {
            SingleMeasureEvaluation measureEvaluation = (SingleMeasureEvaluation) evaluation;
            importFunction(sheet, column, measureEvaluation);
        } else {
            WeightedSumMultiMeasureEvaluation measureEvaluation = (WeightedSumMultiMeasureEvaluation) evaluation;
            if (measureEvaluation == null) {
                System.err.println("Evaluation not found. Model and Excel file are inconsistent.");
            } else {
                String measureName = sheet.getRow(1).getCell(column).getStringCellValue();
                MeasureRanking measureRanking = getMeasureRanking(measureEvaluation, measureName);

                importFunction(sheet, column, measureRanking);
            }
        }
        monitor.worked(1);
    }
}

From source file:de.quamoco.qm.editor.export.ResultCalibrationImporter.java

License:Apache License

/** Calibrate a {@link FactorAggregation}. */
private void importFactorAggregationCalibration(Sheet sheet, EAttribute attribute, IProgressMonitor monitor) {
    Row mainRow = sheet.getRow(0);
    for (Iterator<Cell> i = mainRow.cellIterator(); i.hasNext();) {
        Cell cell = i.next();//from www.  j a  v a 2s .  c om
        int column = cell.getColumnIndex();
        if (column < 1) {
            continue;
        }
        String id = cell.getStringCellValue();
        EObject evaluation = getEvaluation(id);
        if (evaluation instanceof WeightedSumFactorAggregation) {
            WeightedSumFactorAggregation factorAggregation = (WeightedSumFactorAggregation) evaluation;
            importWeightedSumFactorAggregation(sheet, factorAggregation, attribute, column);
        } else {
            WeightedSumMultiMeasureEvaluation multiMeasureEvaluation = (WeightedSumMultiMeasureEvaluation) evaluation;
            importWeightedSumMultiMeasureEvaluation(sheet, multiMeasureEvaluation, attribute, column);
        }
        monitor.worked(1);
    }
}

From source file:de.tum.in.socket.server.ReadExcel.java

License:Apache License

/**
 * Returns the excel column names/*from  www. ja v  a2 s  .  co  m*/
 */
private static String[] getColumnNames(final Row column) {
    final String columns[] = new String[column.getPhysicalNumberOfCells()];
    final Iterator<Cell> cellIterator = column.cellIterator();
    int i = 0;
    while (cellIterator.hasNext()) {
        final Cell cell = cellIterator.next();
        columns[i++] = cell.getStringCellValue();
    }
    return columns;
}

From source file:de.tum.in.socket.server.ReadExcel.java

License:Apache License

/**
 * Loads the retrieved data from excel to the list
 *//*from w  ww  .j av a  2  s  . c om*/
private static List<RealtimeData> loadDataToList(final XSSFSheet sheet, final List<RealtimeData> data,
        final RealtimeData bluetoothData)
        throws InstantiationException, IllegalAccessException, SecurityException, NoSuchFieldException {

    final Row column = sheet.getRow(0);
    final String columnNames[] = getColumnNames(column);

    final Iterator<Row> rowIterator = sheet.iterator();

    int rowOne = 0;

    while (rowIterator.hasNext()) {
        final Row row = rowIterator.next();
        final Iterator<Cell> cellIterator = row.cellIterator();

        final RealtimeData newRecord = bluetoothData.getClass().newInstance();

        if (rowOne > 0) {
            int i = 0;
            while (cellIterator.hasNext()) {
                final Cell cell = cellIterator.next();
                final String columnName = columnNames[i++];
                final Field f1 = bluetoothData.getClass().getDeclaredField(columnName.trim());
                f1.setAccessible(true);
                f1.set(newRecord, getTypeValue(f1.getType(), cell));
            }
            data.add(newRecord);
        }
        rowOne++;
    }
    return data;

}

From source file:dias.m20150711_get_armband_data.java

public Matrix m20150711_get_armband_data() {

    eedouble = 0;//from  ww  w .  j a v a  2s .  c o m
    gsrdouble = 0;
    phys_actdouble = 0;
    sleepdouble = 0;

    try {
        FileInputStream file = new FileInputStream(new File(DIAS.bodymediaFileUrl));

        HSSFWorkbook workbook = new HSSFWorkbook(file);

        HSSFSheet sheet = workbook.getSheetAt(0);

        Iterator<Row> rowIterator = sheet.iterator();
        int s = 0;
        int i = 0;
        int j = 0;
        int kx = 0;
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<org.apache.poi.ss.usermodel.Cell> cellIterator = row.cellIterator();
            i++;
            s = 0;
            while (cellIterator.hasNext()) {
                j++;
                org.apache.poi.ss.usermodel.Cell cell = cellIterator.next();
                switch (cell.getCellType()) {
                case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN:
                    break;
                case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC:
                    armband_data.set(i, j, cell.getNumericCellValue());

                    if (kx == 28)
                        armband_data_with_time.set(i, 5, cell.getNumericCellValue()); // Heat-Flux Average

                    if (kx == 27)
                        armband_data_with_time.set(i, 4, cell.getNumericCellValue()); //Sleep Classification

                    if (kx == 26)
                        armband_data_with_time.set(i, 3, cell.getNumericCellValue()); //Activity Class

                    if (kx == 25)
                        armband_data_with_time.set(i, 2, cell.getNumericCellValue()); //Distance

                    if (kx == 24)
                        armband_data_with_time.set(i, 1, cell.getNumericCellValue()); //Speed

                    if (kx == 23)
                        armband_data_with_time.set(i, 0, cell.getNumericCellValue()); //MET 's

                    kx++;

                    break;

                case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING:
                    if (cell.getStringCellValue().equals("NAN")) {
                        if (s == 0) {
                            i--;
                            s = 1;
                        }
                    }
                    break;
                }
            }
            kx = 0;
            j = 0;
        }

        file.close();
        s = 0;

        eedouble = 0;
        gsrdouble = 0;
        sleepdouble = 0;
        phys_actdouble = 0;

        eedouble = armband_data.get(7164, 18);
        gsrdouble = armband_data.get(7164, 14);
        sleepdouble = armband_data.get(7164, 16);
        phys_actdouble = armband_data.get(7164, 17);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return armband_data;

}

From source file:ec.mil.he1.mbeans.JSFManagedBeanFileUpload.java

public String convertjava() {
    grabar = "0";
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {/*w w w. j  ava 2 s . c  o  m*/
        connection = he1_pool.getConnection();

        String sql = "Insert into CODIGO_MIFIN(CEDULA, CODIGO, MES , MES_NUMERO, ANIO , DESCRIPCION, ARCHIVO)  Values   "
                + " (?, ?, ?, ? , ?, ? , ? )";
        int columna = 0;

        /*PrepareStatement*/
        preparedStatement = connection.prepareStatement(sql);

        //variables donde cargar los datos por cada celda
        String cc = "";
        String codigo = "";
        String mes = "";
        String mes_numero = "";
        String anio = "";
        String descripcion = "";

        file = (FileInputStream) inputstream;

        // Get the workbook instance for XLS file
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        sheet = workbook.getSheetAt(0);
        // Iterate through each rows from first sheet
        Iterator<org.apache.poi.ss.usermodel.Row> rowIterator = sheet.rowIterator();
        //aca se barre todas las filas
        while (rowIterator.hasNext()) {

            org.apache.poi.ss.usermodel.Row row = rowIterator.next();
            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            //aca se tiene las columnas por ello encero
            columna = 0;
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();

                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    cell.getBooleanCellValue();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    cell.getNumericCellValue();
                    break;
                case Cell.CELL_TYPE_STRING:
                    cell.getStringCellValue();
                    break;
                }

                if (columna == 0) {
                    cc = cell.getStringCellValue();

                } else if (columna == 1) {
                    codigo = cell.getStringCellValue();

                } else if (columna == 2) {
                    mes = cell.getStringCellValue();

                } else if (columna == 3) {
                    mes_numero = cell.getStringCellValue();

                } else if (columna == 4) {
                    anio = cell.getStringCellValue();

                } else if (columna == 5) {
                    descripcion = cell.getStringCellValue();

                }

                columna++;
            }
            preparedStatement.setString(1, cc);
            preparedStatement.setString(2, codigo);
            preparedStatement.setString(3, mes);
            preparedStatement.setString(4, mes_numero);
            preparedStatement.setString(5, anio);
            preparedStatement.setString(6, descripcion);
            preparedStatement.setString(7, nombre_archivo);
            preparedStatement.addBatch();
            cc = "";
            codigo = "";
            mes = "";
            mes_numero = "";
            anio = "";
            descripcion = "";
            System.out.println("");
        }
        file.close();
        int[] affectedRecords = preparedStatement.executeBatch();
        addMessage("Se ha cargado la informacin en el sistema");

    } catch (IOException ex) {
        Logger.getLogger(JSFManagedBeanFileUpload.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(JSFManagedBeanFileUpload.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
                preparedStatement = null;
            } catch (SQLException ex) {
                Logger.getLogger(JSFManagedBeanFileUpload.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException ex) {
                Logger.getLogger(JSFManagedBeanFileUpload.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return null;
}