Example usage for org.apache.poi.ss.usermodel Sheet getSheetName

List of usage examples for org.apache.poi.ss.usermodel Sheet getSheetName

Introduction

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

Prototype

String getSheetName();

Source Link

Document

Returns the name of this sheet

Usage

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

License:Open Source License

/**
 * first pass: only create types.//from ww  w . j  a  v a 2s  .  co  m
 * 
 * Read the given sheet, and analyze the type defined on this sheet.
 *
 * @param sheet the Excel sheet.
 */
private void importMetamodelTypes(Sheet sheet) {

    if (sheet.getSheetName().equals(DataExportIntroSheetGenerator.INTRO_SHEET_NAME)) {
        LOGGER.info("Intro");
        return;
    }

    String typeString = null;
    if (sheet.getRow(SHEET_TYPE_ROW_NO) != null && sheet.getRow(SHEET_TYPE_ROW_NO).getCell(0) != null) {
        typeString = ExcelUtils.getStringCellValue(sheet.getRow(SHEET_TYPE_ROW_NO).getCell(0));
    } else {
        logError("Sheet {0}: Sheet Type not defined", sheet.getSheetName());
        return;
    }

    TypeExpressionReader ter = new TypeExpressionReader(typeString);

    LOGGER.info("Sheet {0}: Type: {1}, Metatype {2}", sheet.getSheetName(), ter.getTypeName(),
            ter.getMetaTypeName());

    NamedExpression expr = null;
    if (ter.getMetaTypeName().equals("SubstantialTypeExpression")) {
        expr = metamodel.createSubstantialType(ter.getTypeName());
    } else if (ter.getMetaTypeName().equals("RelationshipTypeExpression")) {
        expr = metamodel.createRelationshipType(ter.getTypeName());
    } else if (ter.getMetaTypeName().equals("EnumerationExpression")) {
        expr = metamodel.createEnumeration(ter.getTypeName());
    } else if (ter.getMetaTypeName().equals("RelationshipExpression")) {
        relationshipSheets.add(sheet);
    } else {
        logError("Sheet {0}: cannot deal with metatype {1}", sheet.getSheetName(), ter.getMetaTypeName());
        return;
    }

    if (expr != null) {
        String nameString;
        if (expr instanceof EnumerationExpression) {
            //it doesn't make sense to use an abbreviation on an EnumerationExpression,
            //so it takes the name as it is from the cell, without calling readNameString()
            //REVIEW <ITERAPLAN-1612>: TODO Abbreviations for enumeration types should be supported in later versions, when that happens, this piece of code must be reviewed again.

            nameString = ExcelUtils.getStringCellValue(sheet.getRow(0).getCell(0));
        } else {
            // strip the type abbreviation from the name
            nameString = readNameString(sheet);
        }
        expr.setName(nameString);
        expr.setAbbreviation(ter.getAbbreviation());
        expr.setDescription(readDescription(sheet));
        SheetContext sheetContext = new SheetContext(sheet, expr);
        wbContext.addSheetContext(sheetContext);
    }
}

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

License:Open Source License

/**
 * also second pass: import relationships.
 * /*from www. j av  a 2  s .  co  m*/
 * @param sheet the excel sheet; this sheet must have a relationship expression.
 */
private void importRelationshipSheet(Sheet sheet) {
    try {
        new RelationSheetImporter(metamodel).importMetamodelRelationTypeSpecification(sheet);
    } catch (ElasticeamException e) {
        logError("Sheet {0}: Import error: {1}", sheet.getSheetName(), e.getMessage());
    }
}

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

License:Open Source License

/**
 * do the import of the relations on the given sheet.
 * //  ww w  . j a v a2  s  .  c  om
 * @param sheet
 */
public void importRelationData(Sheet sheet) {
    LOGGER.info("    == Pass 4: Sheet {0}", sheet.getSheetName());

    String typeString = ExcelUtils.getStringCellValue(sheet.getRow(SHEET_TYPE_ROW_NO).getCell(0));
    TypeExpressionReader ter = new TypeExpressionReader(typeString);

    if (!"RelationshipExpression".equals(ter.getMetaTypeName())) { // TODO tse: hard coded name ok?
        logError("Unexpected sheet {0} with expression: {1}", sheet.getSheetName(), ter.getMetaTypeName());
        return;
    }

    String fromString = ExcelUtils.getStringCellValue(sheet.getRow(FEATURE_TYPE_ROW_NO).getCell(0));
    String toString = ExcelUtils.getStringCellValue(sheet.getRow(FEATURE_TYPE_ROW_NO).getCell(1));

    FeatureExpressionReader fromFER = new FeatureExpressionReader(fromString);
    FeatureExpressionReader toFER = new FeatureExpressionReader(toString);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Create Relation: From {0} to {1}", fromFER.getTypeName(), toFER.getTypeName());
    }

    SubstantialTypeExpression fromType = (SubstantialTypeExpression) metamodel
            .findTypeByPersistentName(fromFER.getTypeName());
    SubstantialTypeExpression toType = (SubstantialTypeExpression) metamodel
            .findTypeByPersistentName(toFER.getTypeName());

    if (fromType != null && toType != null) {
        RelationshipEndExpression expr = (RelationshipEndExpression) fromType
                .findFeatureByPersistentName(toFER.getPersistentName());

        if (expr == null) {
            RelationshipExpression rel = metamodel.createRelationship(ter.getTypeName(), //
                    toType, fromFER.getPersistentName(), fromFER.getLowerBound(), fromFER.getUpperBound(), //
                    fromType, toFER.getPersistentName(), toFER.getLowerBound(), toFER.getUpperBound());
            expr = rel.findRelationshipEndByPersistentName(toFER.getPersistentName());
        }

        if (expr != null) {
            boolean hasMore = true;
            for (int rowNum = FIRST_DATA_ROW_NO; hasMore; rowNum++) {
                Row row = sheet.getRow(rowNum);
                hasMore = importRelation(row, fromType, toType, expr);
            }
        }
    } else {
        String missingType = (fromType == null) ? fromFER.getPersistentName() : toFER.getPersistentName();
        logError("Sheet \"{0}\": Could not import Relation \"{1}-{2}\". Type for {3} doesn't exist.",
                sheet.getSheetName(), fromFER.getPersistentName(), toFER.getPersistentName(), missingType);
    }
}

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

License:Open Source License

/**
 * import the relationship expression and add it to the meta model.
 * /*from  w  w w . j a  va 2  s.  c om*/
 * If there are errors, these errors are logged, but the import will continue.
 * 
 * @param sheetContext sheet to import. The expression type of this sheet <b>must</b> be 
 *        a {@link RelationshipExpression}.
 */
/* package*/void importMetamodelRelationTypeSpecification(Sheet sheet) {
    Row featureTypeRow = sheet.getRow(FEATURE_TYPE_ROW_NO);
    Cell fromCell = featureTypeRow.getCell(0);
    Cell toCell = featureTypeRow.getCell(1);

    FeatureExpressionReader fromFER = new FeatureExpressionReader(ExcelUtils.getStringCellValue(fromCell));
    FeatureExpressionReader toFER = new FeatureExpressionReader(ExcelUtils.getStringCellValue(toCell));

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Sheet {0}: Create relationship: FROM: {1} --> TO: {2}", sheet.getSheetName(),
                fromFER.toString(), toFER.toString());
    }

    String relationshipName = createRelationshipName(fromFER, toFER);
    UniversalTypeExpression fromType = metamodel.findUniversalTypeByPersistentName(fromFER.getTypeName());
    UniversalTypeExpression toType = metamodel.findUniversalTypeByPersistentName(toFER.getTypeName());

    try {
        RelationshipExpression rel = metamodel.createRelationship(relationshipName, //
                fromType, toFER.getPersistentName(), toFER.getLowerBound(), toFER.getUpperBound(), //
                toType, fromFER.getPersistentName(), fromFER.getLowerBound(), fromFER.getUpperBound());

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("created RelationshipExpression: {0}", rel.toString());
        }
    } catch (MetamodelException e) {
        LOGGER.error("caught Metamodel Exception:", e);
        String message = e.getMessage();
        if (fromType == null || toType == null) {
            String missingType = (fromType == null) ? fromFER.getPersistentName() : toFER.getPersistentName();
            message = MessageFormat.format(
                    "Sheet \"{0}\": Could not import Relation \"{1}-{2}\". Type for {3} doesn't exist.",
                    sheet.getSheetName(), fromFER.getPersistentName(), toFER.getPersistentName(), missingType);
        }
        throw new MetamodelException(ElasticeamException.GENERAL_ERROR, message, e);
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.util.ExcelUtils.java

License:Open Source License

/**
 * Returns a CellReference containing the given sheet's sheet name,
 * and row and column of the given cell reference
 * @param sheet/*from w  w  w.  j a va  2 s . co  m*/
 * @param cellReference
 * @return The CellReference including the sheet name
 */
public static CellReference getFullCellReference(Sheet sheet, CellReference cellReference) {
    return new CellReference(sheet.getSheetName(), cellReference.getRow(), cellReference.getCol(), true, true);
}

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

License:Open Source License

/**
 * Imports the data out of the specified Excel file input stream. If data
 * could not be imported, an {@code empty} list will be returned.
 * // ww w  . jav a  2 s.c o m
 * @param is the Excel file input stream
 * @return the list of imported object related permission data objects
 */
public AttributeData doImport(InputStream is) {
    AttributeData result = new AttributeData();

    loadWorkbookFromInputStream(is);
    initSheetImporters();
    initAttributeTypeHeadlines();

    if (!readInConfigSheet()) {
        getProcessingLog().error("Could not read in configuration sheet. Aborting.");
        return result;
    }

    calculateAllFormulas();
    for (int i = 0; i < getWb().getNumberOfSheets(); i++) {
        Sheet sheet = getWb().getSheetAt(i);
        String sheetName = sheet.getSheetName();

        getProcessingLog().info("Current Sheet: " + StringUtils.defaultIfEmpty(sheetName, "null"));

        if (DEFAULT_SHEET_KEY.equals(sheetName)) {
            continue;
        }

        if (!SHEET_IMPORTER.containsKey(sheetName)) {
            getProcessingLog().error("No import is available for this sheet.");
            continue;
        }

        importSheet(sheet, result);
    }

    return result;
}

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

License:Open Source License

/**
 * Imports the data from the specified {@code sheet}.
 * @param sheet the sheet to import the data from
 * @param attributeData Container for imported Attributes
 *//*from  w w  w. j  a va 2 s . c o  m*/
private void importSheet(Sheet sheet, AttributeData attributeData) {
    getProcessingLog().debug("Importing Sheet: " + sheet.getSheetName());

    String headColumnName = MessageAccess.getStringOrNull(NAME_COLUMN_KEY, getLocale());
    int contentPosition = findSheetContentPosition(sheet, headColumnName, 0);
    if (contentPosition != -1) {
        Row headRow = sheet.getRow(contentPosition - 1);

        List<String> tmp = ATTRIBUTE_TYPE_HEADLINES.get(sheet.getSheetName());
        Map<String, Integer> headline = ExcelImportUtilities.getHeadlineForRange(headRow, new int[] { 0, 12 },
                getProcessingLog());

        for (String columnName : tmp) {
            if (!headline.containsKey(columnName)) {
                getProcessingLog().error(
                        "Attribute column {0} is missing for {1}. Partial import is not possible.", columnName,
                        sheet.getSheetName());
                continue;
            }
        }

        List<Row> sheetContentRows = getSheetContentRows(contentPosition, sheet);

        AttributeSheetImporter<?> importer = SHEET_IMPORTER.get(sheet.getSheetName());
        importer.readContentFromSheet(sheetContentRows, headline, attributeData);
    } else {
        getProcessingLog().warn("Invalid structure of Sheet '" + sheet.getSheetName() + "', skipping");
    }
}

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

License:Open Source License

/**
 * Initially reads the complete Excel workbook and calculates all formulaCells. After that, we can
 * be sure that no cell contains formulas any longer, but they all contain values (or nothing).
 *///ww  w .ja v a 2  s. c  o  m
protected void calculateAllFormulas() {
    FormulaEvaluator evaluator = new HSSFFormulaEvaluator((HSSFWorkbook) getWb());

    // iterate over all sheets, their rows, and all their cells
    for (int sheetNum = 0; sheetNum < getWb().getNumberOfSheets(); sheetNum++) {
        Sheet sheet = getWb().getSheetAt(sheetNum);

        for (Row row : sheet) {
            for (Cell cell : row) {

                if ((cell.getCellType() == Cell.CELL_TYPE_FORMULA) && (cell.getCellFormula() != null)) {
                    try {
                        evaluator.evaluateInCell(cell);
                    } catch (Exception e) {
                        getProcessingLog().error("Error calculating the formula in cell ["
                                + ExcelImportUtilities.getCellRef(cell) + "] on sheet '" + sheet.getSheetName()
                                + "', using cached value instead: " + e.getLocalizedMessage());
                    }
                }
            }
        }
    }
}

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

License:Open Source License

/**
 * Reads the specified {@code excelInputStream} and returns the landscape data
 * as {@link LandscapeData} object, containing the building blocks, relations and
 * attributes. If the import failes, or no data could be found, this method
 * returns an empty landscape data object.
 * /*from w w  w  .j av  a 2s .co  m*/
 * @param excelInputStream the Excel file input stream
 * @return the {@link LandscapeData} object containing building blocks, relations and attributes
 */
public LandscapeData doImport(InputStream excelInputStream) {
    loadWorkbookFromInputStream(excelInputStream);
    final LandscapeData landscapeData = new LandscapeData();

    if (!readInConfigSheet()) {
        getProcessingLog().error("Could not read in configuration sheet. Aborting.");
        landscapeData.setLocale(getLocale());
        return landscapeData;
    }

    // we can only initialize the sheet importers *after* the locale was read in from the config sheet
    initSheetImporters();

    calculateAllFormulas();

    for (int i = 0; i < getWb().getNumberOfSheets(); i++) {
        Sheet sheet = getWb().getSheetAt(i);
        String sheetName = sheet.getSheetName();

        getProcessingLog().insertDummyRow("");

        getProcessingLog().debug("Current Sheet: " + (sheetName == null ? "null" : sheetName));

        if (isSheetSupported(sheetName)) {
            final String idKey = MessageAccess.getStringOrNull("global.id", getLocale());
            int contentPosition = findSheetContentPosition(sheet, idKey, 0);
            if (contentPosition != -1) {
                importSheet(sheet, contentPosition, landscapeData);
            } else {
                getProcessingLog().warn("Invalid structure of Sheet '" + sheetName + "', skipping");

            }
            int contentPositionSubscribed = findSheetContentPosition(sheet,
                    MessageAccess.getStringOrNull(Constants.SUBSCRIBED_USERS, getLocale()), 1);
            Set<User> users = Sets.newHashSet();
            if (contentPositionSubscribed != -1) {
                Row row = sheet.getRow(contentPositionSubscribed - 1);
                if (row.getPhysicalNumberOfCells() > 1) {
                    String subUsers = row.getCell(2, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
                    if (StringUtils.isNotEmpty(subUsers)) {
                        Set<String> logins = Sets.newHashSet(ExcelImportUtilities.getSplittedArray(subUsers,
                                ExcelSheet.IN_LINE_SEPARATOR.trim()));
                        for (String login : logins) {
                            User user = new User();
                            user.setLoginName(login);
                            users.add(user);
                        }
                    }
                }
            }
            TypeOfBuildingBlock type = sheetToTypeMapping.get(sheetName);
            landscapeData.getUsers().put(type, users);
        } else if (!DEFAULT_SHEET_KEY.equals(sheetName)) {
            getProcessingLog().warn("Unknown Sheet Name '" + sheetName + "'(different Locale?). Skipping.");
        }
    }

    landscapeData.setLocale(getLocale());

    return landscapeData;
}

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

License:Open Source License

/**
 * Creates appropriate specific class for that sheetName/Type, which automatically starts
 * importing its data/*from  w w  w  .  ja va2s .c o  m*/
 */
private void importSheet(Sheet sheet, int contentRowOffset, LandscapeData landscapeData) {
    String sheetName = sheet.getSheetName();
    getProcessingLog().debug("Importing Sheet: " + sheetName);

    SheetImporter<?> sheetImporter = sheetImporters.get(sheetName);
    if (sheetImporter == null) {
        getProcessingLog().error(" Sheet Name '" + sheetName + "' not supported, skipping");
        return;
    }

    Permissions permissions = UserContext.getCurrentPerms();
    TypeOfBuildingBlock tobb = sheetImporter.getTypeOfBuildingBlockOnSheet();
    if (!permissions.userHasBbTypeUpdatePermission(tobb) || !permissions.userHasBbTypeCreatePermission(tobb)) {
        String tobbStr = MessageAccess.getStringOrNull(tobb.getPluralValue(), getLocale());
        getProcessingLog().error(
                "You have no update and create permissions for the building block {0}, skipping sheet {1}.",
                tobbStr, sheetName);
        return;
    }

    final int headRowIndex = contentRowOffset - 1;
    sheetImporter.doImport(sheet, contentRowOffset, headRowIndex, landscapeData);
}