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

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

Introduction

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

Prototype

Sheet getSheet();

Source Link

Document

Returns the Sheet this row belongs to

Usage

From source file:com.streamsets.pipeline.lib.parser.excel.WorkbookParser.java

License:Apache License

@Override
public Record parse() throws DataParserException {
    if (!rowIterator.hasNext()) {
        eof = true;//from   w w w  .  ja va  2  s .c  o m
        return null;
    }

    Row currentRow = rowIterator.next();

    // skip over rows that have cells but all cells are of BLANK celltype.
    while (rowIsBlank(currentRow)) {
        if (rowIterator.hasNext()) {
            currentRow = rowIterator.next();
        } else {
            // end of file and this last row is blank.  Bail out.
            eof = true;
            return null;
        }
    }

    // see if a new worksheet has been entered.
    if (this.currentSheet == null || !this.currentSheet.equals(currentRow.getSheet().getSheetName())) {
        this.currentSheet = currentRow.getSheet().getSheetName();
        // if header is expected, then jump over this row
        if (settings.getHeader() == ExcelHeader.WITH_HEADER
                || settings.getHeader() == ExcelHeader.IGNORE_HEADER) {
            currentRow = rowIterator.next(); // move to the next row to parse as data
        }
    }

    offset = Offsets.offsetOf(currentRow);
    Record record = context.createRecord(offset);
    updateRecordWithCellValues(currentRow, record);
    return record;
}

From source file:com.streamsets.pipeline.lib.parser.excel.WorkbookParser.java

License:Apache License

private void updateRecordWithCellValues(Row row, Record record) throws DataParserException {
    LinkedHashMap<String, Field> output = new LinkedHashMap<>();
    String sheetName = row.getSheet().getSheetName();
    String columnHeader;//  w w  w .ja  v a2 s . co m
    Set<String> unsupportedCellTypes = new HashSet<>();
    for (int columnNum = row.getFirstCellNum(); columnNum < row.getLastCellNum(); columnNum++) {
        if (headers.isEmpty()) {
            columnHeader = String.valueOf(columnNum);
        } else {
            if (columnNum >= headers.get(sheetName).size()) {
                columnHeader = String.valueOf(columnNum); // no header for this column.  mismatch
            } else {
                columnHeader = headers.get(sheetName).get(columnNum).getValueAsString();
            }
        }

        Cell cell = row.getCell(columnNum, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        try {
            output.put(columnHeader, Cells.parseCell(cell, this.evaluator));
        } catch (ExcelUnsupportedCellTypeException e) {
            output.put(columnHeader, Cells.parseCellAsString(cell));
            unsupportedCellTypes.add(e.getCellType().name());
        }
    }

    // Set interesting metadata about the row
    Record.Header hdr = record.getHeader();
    hdr.setAttribute("worksheet", row.getSheet().getSheetName());
    hdr.setAttribute("row", Integer.toString(row.getRowNum()));
    hdr.setAttribute("firstCol", Integer.toString(row.getFirstCellNum()));
    hdr.setAttribute("lastCol", Integer.toString(row.getLastCellNum()));
    record.set(Field.createListMap(output));
    if (unsupportedCellTypes.size() > 0) {
        throw new RecoverableDataParserException(record, Errors.EXCEL_PARSER_05,
                StringUtils.join(unsupportedCellTypes, ", "));
    }
}

From source file:com.vaadin.addon.spreadsheet.command.RowData.java

private void copyCellsData(Row row) {
    for (Cell cell : row) {
        if (cell == null) {
            continue;
        } else {/*from ww w.  j a  v a2s  .c o m*/
            CellData cellData = new CellData(spreadsheet);
            cellData.read(cell);
            cellsData.add(cellData);
        }
    }

    for (int i = 0; i < maxCol; ++i) {
        Comment cellComment = row.getSheet().getCellComment(row.getRowNum(), i);
        Cell cell = row.getCell(i);
        if (cellComment != null && cell == null) {
            CommentData commenData = new CommentData();
            commenData.read(cellComment);
            commentsWithoutCell.add(commenData);
        }
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.excelimport.RelationDataImporter.java

License:Open Source License

/**
 * @param row//from  w  w w  .j  a  va2  s .c om
 * @param ferFrom
 * @param ferTo
 * 
 * @return true if this method did an import, false if it hit an empty row.
 */
private boolean importRelation(Row row, SubstantialTypeExpression fromType, SubstantialTypeExpression toType,
        RelationshipEndExpression expr) {
    if (row == null || row.getCell(0) == null || ExcelUtils.isEmptyCell(row.getCell(0))) {
        return false;
    }

    String fromName = getName(row.getCell(0), fromType);
    String toName = getName(row.getCell(1), toType);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Relation: From {0}[{1}] to {2}[{3}] via {4}[{5}]", fromType.getPersistentName(), fromName, //
                toType.getPersistentName(), toName, //
                expr.getType().getPersistentName(), expr.getName());
    }

    UniversalModelExpression fromInstance = model.findByName(fromType, fromName);
    UniversalModelExpression toInstance = model.findByName(toType, toName);

    if (fromInstance == null || toInstance == null) {
        logError("Sheet \"{0}\", row {1}: fromInstance {2} or toInstance {3} is null!",
                row.getSheet().getSheetName(), Integer.valueOf(row.getRowNum() + 1), fromInstance, toInstance);
    } else {
        LOGGER.debug("About to create relation: from {0} to {1}", fromInstance, toInstance);
        fromInstance.connect(expr, toInstance);
    }

    return true;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.importer.ObjectRelatedPermissionsWorkbook.java

License:Open Source License

private List<ObjectRelatedPermissionsData> readContentFromSheet(List<Row> sheetContentRows,
        Map<String, Integer> headline, TypeOfBuildingBlock typeOfBuildingBlock) {
    final List<ObjectRelatedPermissionsData> result = Lists.newArrayList();

    for (Row row : sheetContentRows) {
        LOGGER.debug(" " + row.getSheet().getSheetName() + ": Row " + row.getRowNum());

        Map<String, Cell> rowContent = ExcelImportUtilities.readRow(row, headline);
        ObjectRelatedPermissionsData userPermissions = parseRow(rowContent, typeOfBuildingBlock,
                row.getRowNum() + 1);//from  w  ww.  j a va2 s .co  m

        if (userPermissions != null) {
            result.add(userPermissions);
        }
    }

    return result;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.timeseriesExcel.importer.TimeseriesExcelImporter.java

License:Open Source License

private BuildingBlock getBuildingBlock(Row row, BuildingBlockService<BuildingBlock, Integer> bbService) {
    Cell cell = row.getCell(BB_COL_NO);/*w  w w .j  a va  2 s.c o m*/

    if (ExcelUtils.isEmptyCell(cell)) {
        logError(ExcelUtils.getFullCellReference(row.getSheet(), new CellReference(row.getRowNum(), BB_COL_NO)),
                "No Building Block found.");
        return null;
    }

    String bbName = StringUtils.trim(ExcelUtils.getStringCellValue(cell));
    List<BuildingBlock> bbList = bbService.findByNames(Collections.singleton(bbName));

    if (bbList == null || bbList.isEmpty()) {
        logError(ExcelUtils.getFullCellReference(cell), "No Building Block named \"{0}\" found.", bbName);
        return null;
    }

    if (bbList.size() > 1) {
        LOGGER.error("More than one Building Block named \"{0}\" found.", bbName);
        throw new IteraplanTechnicalException(IteraplanErrorMessages.GENERAL_TECHNICAL_ERROR);
    }

    return bbList.get(0);
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.timeseriesExcel.importer.TimeseriesExcelImporter.java

License:Open Source License

private Date getDate(Row row) {
    Cell cell = row.getCell(DATE_COL_NO);

    if (ExcelUtils.isEmptyCell(cell)) {
        logError(ExcelUtils.getFullCellReference(row.getSheet(),
                new CellReference(row.getRowNum(), DATE_COL_NO)), "No date value found.");
        return null;
    }/*from   w  ww. j  a  v  a2s .  c o m*/

    Object dateCellValue = ExcelUtils.getCellValue(cell, true);
    if (!(dateCellValue instanceof Date)) {
        logError(ExcelUtils.getFullCellReference(cell), "No date value found.");
        return null;
    } else {
        Date date = (Date) dateCellValue;
        if (now.isBefore(new LocalDate(date))) {
            logError(ExcelUtils.getFullCellReference(cell),
                    "Date is after today. Only past dates or the present day are allowed for timeseries.");
            return null;
        } else {
            return date;
        }
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.timeseriesExcel.importer.TimeseriesExcelImporter.java

License:Open Source License

private String getValue(Row row, boolean isNumberAt) {
    Cell valueCell = row.getCell(VALUE_COL_NO);
    if (ExcelUtils.isEmptyCell(valueCell)) {
        logError(ExcelUtils.getFullCellReference(row.getSheet(),
                new CellReference(row.getRowNum(), VALUE_COL_NO)), "No attribute value found.");
        return null;
    }//  www  . ja va 2 s .c  o  m

    if (isNumberAt) {
        Object value = ExcelUtils.getCellValue(valueCell, false);
        if (!(value instanceof Double)) {
            logError(ExcelUtils.getFullCellReference(valueCell),
                    "Non-number value for number attribute type found.");
            return null;
        }
    }

    return ExcelUtils.getStringCellValue(valueCell);
}

From source file:de.topicmapslab.jexc.eXql.grammar.expression.FunctionExpression.java

License:Apache License

/**
 * Interpretation method for value function
 * //from   www . j  av  a2  s . com
 * @param workBook
 *            the workbook
 * @param row
 *            the row
 * @return the result value of the cell addressed by internal value
 *         expressions
 * @throws JeXcException
 *             thrown if operation fails
 */
private Object interpretValueFunction(Workbook workBook, Row row) throws JeXcException {
    if (getExpressions().size() != 2) {
        throw new JeXcException("Invalid number of contained value expression, expects 2 but was "
                + getExpressions().size() + ".");
    }
    Object oRowIndex = getExpressions().get(0).interpret(workBook, row);
    Object oColumnIndex = getExpressions().get(1).interpret(workBook, row);
    BigInteger rowIndex = LiteralUtils.asInteger(oRowIndex.toString());
    BigInteger columnIndex = LiteralUtils.asInteger(oColumnIndex.toString());
    Sheet sheet = row.getSheet();
    Row r = sheet.getRow(rowIndex.intValue());
    if (r == null) {
        return null;
    }
    Cell c = r.getCell(columnIndex.intValue());
    if (c == null) {
        return null;
    }
    if (c.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        Double d = c.getNumericCellValue();
        Long l = d.longValue();
        /*
         * check if long value represents the same numeric value then the
         * double origin
         */
        if (d.doubleValue() == l.longValue()) {
            return String.valueOf(l);
        }
        return String.valueOf(d);
    } else if (c.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        return c.getStringCellValue();
    } else if (c.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
        return c.getBooleanCellValue();
    }
    return c.getStringCellValue();
}

From source file:de.topicmapslab.jexc.eXql.grammar.expression.FunctionExpression.java

License:Apache License

/**
 * Interpretation method for next function
 * /*from   w  w w  . ja v a2 s . c  om*/
 * @param workBook
 *            the workbook
 * @param row
 *            the row
 * @return the index of the next row satisfying the given property or in
 *         maximum the last row
 * @throws JeXcException
 *             thrown if operation fails
 */
private Object interpretNextFunction(Workbook workBook, Row row) throws JeXcException {
    ExqlExpression ex = getExpressions().get(0);

    Sheet sheet = row.getSheet();
    for (int i = row.getRowNum() + 1; i < sheet.getLastRowNum() + 1; i++) {
        Row r = sheet.getRow(i);
        Object result = ex.interpret(workBook, Arrays.asList(new Row[] { r }));
        if (result instanceof Collection && !((Collection<?>) result).isEmpty()) {
            return r.getRowNum();
        }
    }
    /*
     * get maximum rows
     */
    return sheet.getLastRowNum() + 1;
}