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

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

Introduction

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

Prototype

Sheet getSheet(String name);

Source Link

Document

Get sheet with the given name

Usage

From source file:org.datanucleus.store.excel.ExcelUtils.java

License:Open Source License

/**
 * Convenience method to return the worksheet used for storing the specified object.
 * @param op ObjectProvider for the object
 * @param wb Workbook//ww  w. ja  v  a 2 s .c  om
 * @param table The table representing this worksheet
 * @return The Work Sheet
 * @throws NucleusDataStoreException if the work sheet doesn't exist in this workbook
 */
public static Sheet getSheetForClass(ObjectProvider op, Workbook wb, Table table) {
    String sheetName = table.getName();
    final Sheet sheet = wb.getSheet(sheetName);
    if (sheet == null) {
        throw new NucleusDataStoreException(
                Localiser.msg("Excel.SheetNotFoundForWorkbook", sheetName, op.getObjectAsPrintable()));
    }
    return sheet;
}

From source file:org.datanucleus.store.excel.ExcelUtils.java

License:Open Source License

/**
 * Convenience method to find the row number of an object in the provided workbook.
 * For application-identity does a search for a row with the specified PK field values.
 * For datastore-identity does a search for the row with the datastore column having the specified value
 * @param op ObjectProvider for the object
 * @param wb Workbook/*  www.j a v  a  2  s  . co m*/
 * @param originalValue Use the original value of the identifiying fields if available (for when we are updating and using nondurable identity).
 * @param table The table representing this worksheet
 * @return The row number (or -1 if not found)
 */
public static int getRowNumberForObjectInWorkbook(ObjectProvider op, Workbook wb, boolean originalValue,
        Table table) {
    final AbstractClassMetaData cmd = op.getClassMetaData();
    if (cmd.getIdentityType() == IdentityType.APPLICATION) {
        ExecutionContext ec = op.getExecutionContext();
        ClassLoaderResolver clr = ec.getClassLoaderResolver();
        int[] pkFieldNumbers = cmd.getPKMemberPositions();

        List<Integer> pkFieldColList = new ArrayList(pkFieldNumbers.length);
        List pkFieldValList = new ArrayList(pkFieldNumbers.length);
        List<Class> pkFieldTypeList = new ArrayList(pkFieldNumbers.length);
        for (int i = 0; i < pkFieldNumbers.length; i++) {
            Object fieldValue = op.provideField(pkFieldNumbers[i]);
            AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNumbers[i]);
            RelationType relationType = mmd.getRelationType(clr);
            if (RelationType.isRelationSingleValued(relationType) && mmd.isEmbedded()) {
                // Embedded PC is part of PK (e.g JPA EmbeddedId)
                ObjectProvider embOP = ec.findObjectProvider(fieldValue);
                if (embOP == null) {
                    embOP = ec.getNucleusContext().getObjectProviderFactory().newForEmbedded(ec, fieldValue,
                            false, op, pkFieldNumbers[i]);
                }
                AbstractClassMetaData embCmd = op.getExecutionContext().getMetaDataManager()
                        .getMetaDataForClass(mmd.getType(), clr);
                for (int j = 0; j < embCmd.getNoOfManagedMembers(); j++) {
                    // TODO Support nested embedded
                    AbstractMemberMetaData embMmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(j);
                    List<AbstractMemberMetaData> embMmds = new ArrayList();
                    embMmds.add(mmd);
                    embMmds.add(embMmd);
                    pkFieldColList.add(
                            table.getMemberColumnMappingForEmbeddedMember(embMmds).getColumn(0).getPosition());
                    pkFieldValList.add(embOP.provideField(j));
                    pkFieldTypeList.add(embMmd.getType());
                }
            } else {
                pkFieldColList.add(table.getMemberColumnMappingForMember(mmd).getColumn(0).getPosition());
                pkFieldValList.add(fieldValue);
                pkFieldTypeList.add(mmd.getType());
            }
        }

        String sheetName = table.getName();
        final Sheet sheet = wb.getSheet(sheetName);
        if (sheet != null && sheet.getPhysicalNumberOfRows() > 0) {
            for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum() + 1; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    boolean matches = true;

                    for (int j = 0; j < pkFieldColList.size(); j++) {
                        int colNumber = pkFieldColList.get(j);
                        Object fieldValue = pkFieldValList.get(j);
                        Class fieldType = pkFieldTypeList.get(j);
                        Cell cell = row.getCell(colNumber);
                        if (!cellMatches(cell, fieldType, fieldValue)) {
                            matches = false;
                            break;
                        }
                    }
                    if (matches) {
                        // Found the object with the correct PK values so return
                        return row.getRowNum();
                    }
                }
            }
        }
    } else if (cmd.getIdentityType() == IdentityType.DATASTORE) {
        String sheetName = table.getName();
        final Sheet sheet = wb.getSheet(sheetName);
        int datastoreIdColNo = table.getDatastoreIdColumn().getPosition();
        Object key = IdentityUtils.getTargetKeyForDatastoreIdentity(op.getInternalObjectId());
        if (sheet != null) {
            for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    Cell cell = row.getCell(datastoreIdColNo);
                    if (cell != null && cellMatches(cell, key.getClass(), key)) {
                        return row.getRowNum();
                    }
                }
            }
        }
    } else {
        // Nondurable, so compare all applicable fields
        ExecutionContext ec = op.getExecutionContext();
        ClassLoaderResolver clr = ec.getClassLoaderResolver();
        int[] fieldNumbers = cmd.getAllMemberPositions();

        List<Integer> fieldColList = new ArrayList(fieldNumbers.length);
        List<Class> fieldTypeList = new ArrayList(fieldNumbers.length);
        List fieldValList = new ArrayList(fieldNumbers.length);
        for (int i = 0; i < fieldNumbers.length; i++) {
            AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]);
            RelationType relationType = mmd.getRelationType(clr);
            Object fieldValue = null;
            if (originalValue) {
                Object oldValue = op
                        .getAssociatedValue(ObjectProvider.ORIGINAL_FIELD_VALUE_KEY_PREFIX + fieldNumbers[i]);
                if (oldValue != null) {
                    fieldValue = oldValue;
                } else {
                    fieldValue = op.provideField(fieldNumbers[i]);
                }
            } else {
                fieldValue = op.provideField(fieldNumbers[i]);
            }
            if (RelationType.isRelationSingleValued(relationType) && mmd.isEmbedded()) {
                // Embedded PC is part of PK (e.g JPA EmbeddedId)
                ObjectProvider embOP = ec.findObjectProvider(fieldValue);
                if (embOP == null) {
                    embOP = ec.getNucleusContext().getObjectProviderFactory().newForEmbedded(ec, fieldValue,
                            false, op, fieldNumbers[i]);
                }
                AbstractClassMetaData embCmd = op.getExecutionContext().getMetaDataManager()
                        .getMetaDataForClass(mmd.getType(), clr);
                for (int j = 0; j < embCmd.getNoOfManagedMembers(); j++) {
                    // TODO Support nested embedded
                    AbstractMemberMetaData embMmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(j);
                    List<AbstractMemberMetaData> embMmds = new ArrayList();
                    embMmds.add(mmd);
                    embMmds.add(embMmd);
                    fieldColList.add(
                            table.getMemberColumnMappingForEmbeddedMember(embMmds).getColumn(0).getPosition());
                    fieldTypeList.add(embMmd.getType());
                    fieldValList.add(embOP.provideField(j));
                }
            } else if (relationType == RelationType.NONE) {
                fieldColList.add(table.getMemberColumnMappingForMember(mmd).getColumn(0).getPosition());
                fieldTypeList.add(mmd.getType());
                fieldValList.add(fieldValue);
            }
        }

        String sheetName = table.getName();
        final Sheet sheet = wb.getSheet(sheetName);
        if (sheet != null && sheet.getPhysicalNumberOfRows() > 0) {
            for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum() + 1; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    boolean matches = true;

                    for (int j = 0; j < fieldColList.size(); j++) {
                        int colNumber = fieldColList.get(j);
                        Class fieldType = fieldTypeList.get(j);
                        Object fieldValue = fieldValList.get(j);

                        Cell cell = row.getCell(colNumber);
                        if (!cellMatches(cell, fieldType, fieldValue)) {
                            matches = false;
                            break;
                        }
                    }
                    if (matches) {
                        // Found the object with the correct PK values so return
                        return row.getRowNum();
                    }
                }
            }
        }
    }
    return -1;
}

From source file:org.datanucleus.store.excel.ExcelUtils.java

License:Open Source License

/**
 * Convenience method to find the number of rows in a workbook.
 * This takes into account the fact that it seems to be impossible (with Apache POI 3.0.2)
 * to delete rows from a sheet. Consequently what we do is leave the row but delete
 * all cells. When returning the number of rows this ignores rows that have no cells.
 * @param op ObjectProvider for the object
 * @param wb Workbook//from  w  w w  . ja  va 2 s . c o m
 * @return Number of (active) rows (or 0 if no active rows)
 */
public static int getNumberOfRowsInSheetOfWorkbook(ObjectProvider op, Workbook wb) {
    int numRows = 0;

    final AbstractClassMetaData cmd = op.getClassMetaData();
    Table table = op.getExecutionContext().getStoreManager()
            .getStoreDataForClass(op.getClassMetaData().getFullClassName()).getTable();
    String sheetName = table.getName();
    final Sheet sheet = wb.getSheet(sheetName);
    if (cmd.getIdentityType() == IdentityType.APPLICATION) {
        int[] pkFieldNumbers = cmd.getPKMemberPositions();
        Object[] pkFieldValues = new Object[pkFieldNumbers.length];
        for (int i = 0; i < pkFieldNumbers.length; i++) {
            pkFieldValues[i] = op.provideField(pkFieldNumbers[i]);
        }

        if (sheet != null && sheet.getPhysicalNumberOfRows() > 0) {
            for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum() + 1; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    boolean validRow = true;
                    for (int j = 0; j < pkFieldNumbers.length; j++) {
                        AbstractMemberMetaData pkMmd = cmd
                                .getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNumbers[j]);
                        int colNumber = table.getMemberColumnMappingForMember(pkMmd).getColumn(0).getPosition();
                        Cell cell = row.getCell(colNumber);
                        if (cell == null) {
                            // Valid row. Apache POI would return cell as null if not active
                            validRow = false;
                        }
                    }
                    if (validRow) {
                        numRows++;
                    }
                }
            }
        }
    } else if (cmd.getIdentityType() == IdentityType.DATASTORE) {
        if (sheet != null && sheet.getPhysicalNumberOfRows() > 0) {
            int datastoreIdColNumber = table.getDatastoreIdColumn().getPosition();
            for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum() + 1; i++) {
                Row rrow = sheet.getRow(i);
                Cell cell = rrow.getCell(datastoreIdColNumber);
                if (cell != null) {
                    // Valid row. Apache POI would return cell as null if not active
                    numRows++;
                }
            }
        }
    } else {
        if (sheet != null && sheet.getPhysicalNumberOfRows() > 0) {
            for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum() + 1; i++) {
                Row rrow = sheet.getRow(i);
                Cell cell = rrow.getCell(0); // Use first cell since no identity as such
                if (cell != null) {
                    // Valid row. Apache POI would return cell as null if not active
                    numRows++;
                }
            }
        }
    }

    return numRows;
}

From source file:org.datanucleus.store.excel.query.ExcelCandidateList.java

License:Open Source License

/**
 * Constructor for the lazy loaded Excel candidate list.
 * @param cls The candidate class//from  ww  w . j a  v a2s .  c  om
 * @param subclasses Whether to include subclasses
 * @param ec execution context
 * @param cacheType Type of caching
 * @param mconn Connection to the datastore
 * @param ignoreCache Whether to ignore the cache on object retrieval
 */
public ExcelCandidateList(Class cls, boolean subclasses, ExecutionContext ec, String cacheType,
        ManagedConnection mconn, boolean ignoreCache) {
    super(cls, subclasses, ec, cacheType);
    this.mconn = mconn;
    this.ignoreCache = ignoreCache;

    // Count the instances per class by scanning the associated worksheets
    numberInstancesPerClass = new ArrayList<Integer>();
    ExcelStoreManager storeMgr = (ExcelStoreManager) ec.getStoreManager();
    Iterator<AbstractClassMetaData> cmdIter = cmds.iterator();
    Workbook workbook = (Workbook) mconn.getConnection();
    while (cmdIter.hasNext()) {
        AbstractClassMetaData cmd = cmdIter.next();

        if (!storeMgr.managesClass(cmd.getFullClassName())) {
            // Make sure schema exists, using this connection
            storeMgr.manageClasses(new String[] { cmd.getFullClassName() }, ec.getClassLoaderResolver(),
                    workbook);
        }
        Table table = ec.getStoreManager().getStoreDataForClass(cmd.getFullClassName()).getTable();
        String sheetName = table.getName();
        Sheet sheet = workbook.getSheet(sheetName);
        int size = 0;
        if (sheet != null && sheet.getPhysicalNumberOfRows() > 0) {
            // Take the next row in this worksheet
            int idColIndex = -1;
            if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                int[] pkFieldNums = cmd.getPKMemberPositions(); // TODO Check all pk cols?
                AbstractMemberMetaData pkMmd = cmd
                        .getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNums[0]);
                idColIndex = table.getMemberColumnMappingForMember(pkMmd).getColumn(0).getPosition();
            } else if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                idColIndex = table.getDatastoreIdColumn().getPosition();
            } else {
                idColIndex = 0; // No id column with nondurable, so just take the first
            }

            for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row.getCell(idColIndex) != null) // Omit inactive rows
                {
                    size++;
                }
            }
        }
        numberInstancesPerClass.add(size);
    }
}

From source file:org.datanucleus.store.excel.query.ExcelCandidateList.java

License:Open Source License

protected Object retrieveObjectForIndex(int index) {
    if (index < 0 || index >= getSize()) {
        throw new NoSuchElementException();
    }//from  www  . j a  va2 s . co  m

    Iterator<AbstractClassMetaData> cmdIter = cmds.iterator();
    Iterator<Integer> numIter = numberInstancesPerClass.iterator();
    int first = 0;
    int last = -1;
    while (cmdIter.hasNext()) {
        final AbstractClassMetaData cmd = cmdIter.next();
        int number = numIter.next();
        last = first + number;

        if (index >= first && index < last) {
            // Object is of this candidate type, so find the object
            Table table = ec.getStoreManager().getStoreDataForClass(cmd.getFullClassName()).getTable();
            String sheetName = table.getName();
            Workbook workbook = (Workbook) mconn.getConnection();
            final Sheet worksheet = workbook.getSheet(sheetName);
            if (worksheet != null) {
                int idColIndex = -1;
                if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                    int[] pkFieldNums = cmd.getPKMemberPositions(); // TODO Check all pk cols?
                    AbstractMemberMetaData pkMmd = cmd
                            .getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNums[0]);
                    idColIndex = table.getMemberColumnMappingForMember(pkMmd).getColumn(0).getPosition();
                } else if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                    idColIndex = table.getDatastoreIdColumn().getPosition();
                } else {
                    idColIndex = 0; // No id column with nondurable, so just take the first
                }

                int current = first;
                for (int i = worksheet.getFirstRowNum(); i <= worksheet.getLastRowNum(); i++) {
                    final Row row = worksheet.getRow(i);
                    if (row.getCell(idColIndex) != null) // Omit inactive rows
                    {
                        if (current == index) {
                            // This row equates to the required index
                            final int rowNumber = i;
                            if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                                final FetchFieldManager fm = new FetchFieldManager(ec, cmd, worksheet,
                                        rowNumber, table);
                                Object id = IdentityUtils.getApplicationIdentityForResultSetRow(ec, cmd, null,
                                        false, fm);

                                return ec.findObject(id, new FieldValues() {
                                    // ObjectProvider calls the fetchFields method
                                    public void fetchFields(ObjectProvider op) {
                                        op.replaceFields(cmd.getAllMemberPositions(), fm);
                                    }

                                    public void fetchNonLoadedFields(ObjectProvider sm) {
                                        sm.replaceNonLoadedFields(cmd.getAllMemberPositions(), fm);
                                    }

                                    public FetchPlan getFetchPlanForLoading() {
                                        return null;
                                    }
                                }, null, ignoreCache, false);
                            } else if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                                final FetchFieldManager fm = new FetchFieldManager(ec, cmd, worksheet,
                                        rowNumber, table);
                                Object id = null;
                                Cell idCell = row.getCell(idColIndex);
                                int type = idCell.getCellType();
                                if (type == Cell.CELL_TYPE_STRING) {
                                    String key = idCell.getRichStringCellValue().getString();
                                    id = ec.getNucleusContext().getIdentityManager()
                                            .getDatastoreId(cmd.getFullClassName(), key);
                                } else if (type == Cell.CELL_TYPE_NUMERIC) {
                                    long key = (long) idCell.getNumericCellValue();
                                    id = ec.getNucleusContext().getIdentityManager()
                                            .getDatastoreId(cmd.getFullClassName(), key);
                                }
                                return ec.findObject(id, new FieldValues() {
                                    // ObjectProvider calls the fetchFields method
                                    public void fetchFields(ObjectProvider op) {
                                        op.replaceFields(cmd.getAllMemberPositions(), fm);
                                    }

                                    public void fetchNonLoadedFields(ObjectProvider op) {
                                        op.replaceNonLoadedFields(cmd.getAllMemberPositions(), fm);
                                    }

                                    public FetchPlan getFetchPlanForLoading() {
                                        return null;
                                    }
                                }, null, ignoreCache, false);
                            } else {
                                // Nondurable identity
                                final FetchFieldManager fm = new FetchFieldManager(ec, cmd, worksheet,
                                        rowNumber, table);
                                Object id = new SCOID(cmd.getFullClassName());
                                return ec.findObject(id, new FieldValues() {
                                    // ObjectProvider calls the fetchFields method
                                    public void fetchFields(ObjectProvider op) {
                                        op.replaceFields(cmd.getAllMemberPositions(), fm);
                                    }

                                    public void fetchNonLoadedFields(ObjectProvider sm) {
                                        sm.replaceNonLoadedFields(cmd.getAllMemberPositions(), fm);
                                    }

                                    public FetchPlan getFetchPlanForLoading() {
                                        return null;
                                    }
                                }, null, ignoreCache, false);
                            }
                        }

                        current++;
                    }
                }
            }
        } else {
            first += number;
        }
    }

    return null;
}

From source file:org.datanucleus.store.excel.valuegenerator.IncrementGenerator.java

License:Open Source License

protected ValueGenerationBlock<Long> reserveBlock(long size) {
    if (size < 1) {
        return null;
    }//from ww  w.  j  ava 2  s  .  c  o  m

    // Allocate value(s)
    ManagedConnection mconn = connectionProvider.retrieveConnection();
    List<Long> oids = new ArrayList<Long>();
    try {
        // Create the worksheet if not existing
        Workbook spreadsheetDoc = (Workbook) mconn.getConnection();
        Sheet sheet = spreadsheetDoc.getSheet(worksheetName);
        Row row = null;
        Cell valueCell = null;
        if (sheet == null) {
            if (!storeMgr.getSchemaHandler().isAutoCreateTables()) {
                throw new NucleusUserException(Localiser.msg("040011", worksheetName));
            }

            sheet = spreadsheetDoc.createSheet(worksheetName);
            row = sheet.createRow(0);
            Cell cell = row.createCell(0);
            cell.setCellValue(key);
            valueCell = row.createCell(1);
            valueCell.setCellValue(Double.valueOf(0));
        } else {
            for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum() + 1; i++) {
                Row tblRow = sheet.getRow(i);
                if (tblRow != null) {
                    Cell tblCell = tblRow.getCell(0);
                    if (tblCell.getStringCellValue().equals(key)) {
                        row = tblRow;
                        valueCell = row.getCell(1);
                        break;
                    }
                }
            }
            if (row == null) {
                row = sheet.createRow(sheet.getLastRowNum() + 1);

                Cell cell1 = row.createCell(0);
                cell1.setCellValue(key);
                valueCell = row.createCell(1);
                valueCell.setCellValue(Double.valueOf(0));
            }
        }

        // Update the row
        if (valueCell != null) {
            NucleusLogger.VALUEGENERATION
                    .debug("Allowing " + size + " values for increment generator for " + key);
            long currentVal = (long) valueCell.getNumericCellValue();
            valueCell.setCellValue(Double.valueOf(currentVal + size));
            for (int i = 0; i < size; i++) {
                oids.add(currentVal + 1);
                currentVal++;
            }
        }
    } finally {
        connectionProvider.releaseConnection();
    }
    return new ValueGenerationBlock<Long>(oids);
}

From source file:org.dbflute.logic.manage.freegen.table.xls.DfXlsTableLoader.java

License:Apache License

public DfFreeGenTable loadTable(String requestName, DfFreeGenResource resource, DfFreeGenMapProp mapProp) {
    final Map<String, Object> tableMap = mapProp.getTableMap();
    final Map<String, Map<String, String>> mappingMap = mapProp.getMappingMap();
    if (tableMap == null || tableMap.isEmpty()) {
        String msg = "The tableMap was not found in the FreeGen property: " + requestName;
        throw new DfRequiredPropertyNotFoundException(msg);
    }/*from ww w .  j av a 2s  . c  om*/
    final String sheetName = (String) tableMap.get("sheetName");
    if (sheetName == null) {
        String msg = "The sheetName was not found in the FreeGen property: " + requestName;
        throw new DfRequiredPropertyNotFoundException(msg);
    }
    final Integer rowBeginNumber;
    {
        final String numStr = (String) tableMap.get("rowBeginNumber");
        if (numStr == null) {
            String msg = "The rowBeginNumber was not found in the FreeGen property: " + requestName;
            throw new DfRequiredPropertyNotFoundException(msg);
        }
        rowBeginNumber = Integer.valueOf(numStr);
    }
    final String resourceFile = resource.getResourceFile();
    @SuppressWarnings("unchecked")
    final Map<String, String> columnMap = (Map<String, String>) tableMap.get("columnMap");
    final Workbook workbook = DfXlsFactory.instance().createWorkbook(new File(resourceFile));
    final Sheet sheet = workbook.getSheet(sheetName);
    if (sheet == null) {
        String msg = "Not found the sheet name in the file: name=" + sheetName + " xls=" + resourceFile;
        throw new IllegalStateException(msg);
    }
    final List<Map<String, Object>> columnList = new ArrayList<Map<String, Object>>(); // rows
    for (int i = (rowBeginNumber - 1); i < Integer.MAX_VALUE; i++) {
        final Row row = sheet.getRow(i);
        if (row == null) {
            break;
        }
        final Map<String, Object> beanMap = DfCollectionUtil.newLinkedHashMap();
        final List<DfFreeGenLazyReflector> reflectorList = DfCollectionUtil.newArrayList();
        boolean exists = false;
        for (Entry<String, String> entry : columnMap.entrySet()) {
            final String key = entry.getKey();
            final String value = entry.getValue();
            if (value == null) {
                String msg = "Not found the value of the key in FreeGen " + requestName + ": " + key;
                throw new DfIllegalPropertySettingException(msg);
            }
            if (processColumnValue(requestName, columnMap, row, beanMap, key, value, reflectorList,
                    mappingMap)) {
                exists = true;
            }
        }
        prepareColumnNameConversion(requestName, beanMap, reflectorList);
        if (exists) {
            columnList.add(beanMap);
        } else { // means empty row
            break;
        }
        for (DfFreeGenLazyReflector reflector : reflectorList) {
            reflector.reflect();
        }
    }
    final String tableName = sheetName; // basically unused, also for compatible
    return new DfFreeGenTable(tableMap, tableName, columnList);
}

From source file:org.diffkit.diff.sns.DKPoiSheet.java

License:Apache License

private Sheet getSheet() throws IOException {
    if (_sheet != null)
        return _sheet;
    Workbook workbook = this.getWorkbook();
    _log.debug("workbook->{}", workbook);
    if (workbook == null)
        throw new IOException("couldn't get workbook");
    String requestedName = this.getRequestedName();
    _log.debug("requestedName->{}", requestedName);
    if (requestedName != null) {
        _sheet = workbook.getSheet(requestedName);
        if (_sheet == null)
            throw new IOException(String.format("couldn't find sheet->'%s' in workbook->'%s'", requestedName,
                    this.getFile()));
    } else {/*  ww w. j a va2 s. com*/
        _sheet = workbook.getSheetAt(0);
        _log.debug("no sheet specified, using first sheet");
    }
    _log.debug("_sheet->{}", _sheet);
    return _sheet;
}

From source file:org.drools.decisiontable.parser.xls.ExcelParser.java

License:Apache License

public void parseFile(InputStream inStream) {
    try {/*w  w  w . jav  a2s  .c  o m*/
        Workbook workbook = WorkbookFactory.create(inStream);

        if (_useFirstSheet) {
            Sheet sheet = workbook.getSheetAt(0);
            processSheet(sheet, _listeners.get(DEFAULT_RULESHEET_NAME));
        } else {
            for (String sheetName : _listeners.keySet()) {
                Sheet sheet = workbook.getSheet(sheetName);
                if (sheet == null) {
                    throw new IllegalStateException(
                            "Could not find the sheetName (" + sheetName + ") in the workbook sheetNames.");
                }
                processSheet(sheet, _listeners.get(sheetName));

            }
        }
    } catch (InvalidFormatException e) {
        throw new DecisionTableParseException(
                "An error occurred opening the workbook. It is possible that the encoding of the document did not match the encoding of the reader.",
                e);

    } catch (IOException e) {
        throw new DecisionTableParseException(
                "Failed to open Excel stream, " + "please check that the content is xls97 format.", e);
    }

}

From source file:org.eclipse.emfforms.internal.spreadsheet.core.renderer.EMFFormsSpreadsheetControlRenderer.java

License:Open Source License

/**
 * {@inheritDoc}//  www . jav  a 2  s . c  o m
 *
 * @see org.eclipse.emfforms.spi.spreadsheet.core.EMFFormsAbstractSpreadsheetRenderer#render(org.apache.poi.ss.usermodel.Workbook,
 *      org.eclipse.emf.ecp.view.spi.model.VElement, org.eclipse.emf.ecp.view.spi.context.ViewModelContext,
 *      org.eclipse.emfforms.spi.spreadsheet.core.EMFFormsSpreadsheetRenderTarget)
 */
@Override
public int render(Workbook workbook, VControl vElement, ViewModelContext viewModelContext,
        EMFFormsSpreadsheetRenderTarget renderTarget) {
    Sheet sheet = workbook.getSheet(renderTarget.getSheetName());
    if (sheet == null) {
        sheet = workbook.createSheet(renderTarget.getSheetName());
        setupSheetFormat(sheet);
    }
    Row labelRow = sheet.getRow(0);
    if (labelRow == null) {
        labelRow = sheet.createRow(0);
    }
    Row descriptionRow = sheet.getRow(1);
    if (descriptionRow == null) {
        descriptionRow = sheet.createRow(1);
    }
    Row formatRow = sheet.getRow(2);
    if (formatRow == null) {
        formatRow = sheet.createRow(2);
    }

    final CellStyle readOnly = (CellStyle) viewModelContext.getContextValue(EMFFormsCellStyleConstants.LOCKED);
    final CellStyle readOnlyWrap = (CellStyle) viewModelContext
            .getContextValue(EMFFormsCellStyleConstants.LOCKED_AND_WRAPPED);

    final Cell idCell = labelRow.getCell(0, Row.CREATE_NULL_AS_BLANK);
    idCell.setCellValue(EMFFormsIdProvider.ID_COLUMN);
    idCell.setCellStyle(readOnly);

    final Cell labelCell = labelRow.getCell(renderTarget.getColumn() + 1, Row.CREATE_NULL_AS_BLANK);
    labelCell.setCellStyle(readOnlyWrap);

    final Cell descriptionCell = descriptionRow.getCell(renderTarget.getColumn() + 1, Row.CREATE_NULL_AS_BLANK);
    descriptionCell.setCellStyle(readOnlyWrap);

    final Cell formatCell = formatRow.getCell(renderTarget.getColumn() + 1, Row.CREATE_NULL_AS_BLANK);
    formatCell.setCellStyle(readOnlyWrap);

    try {
        final EMFFormsExportTableParent exportTableParent = (EMFFormsExportTableParent) viewModelContext
                .getContextValue(EMFFormsExportTableParent.EXPORT_TABLE_PARENT);
        VDomainModelReference dmrToResolve = EcoreUtil.copy(vElement.getDomainModelReference());
        if (exportTableParent != null) {
            final VIndexDomainModelReference indexDMR = exportTableParent.getIndexDMRToExtend();
            indexDMR.setTargetDMR(dmrToResolve);

            dmrToResolve = exportTableParent.getIndexDMRToResolve();
        }

        if (labelCell.getCellComment() == null) {
            final EStructuralFeature structuralFeature = emfformsDatabinding
                    .getValueProperty(dmrToResolve, viewModelContext.getDomainModel()).getStructuralFeature();

            writeLabel(vElement, viewModelContext, labelCell, exportTableParent, dmrToResolve,
                    structuralFeature);

            final Comment comment = createComment(workbook, sheet, dmrToResolve, renderTarget.getRow(),
                    renderTarget.getColumn() + 1);
            labelCell.setCellComment(comment);

            writeDescription(viewModelContext, descriptionCell, dmrToResolve);

            writeFormatInformation(formatCell, structuralFeature);
        }
        if (viewModelContext.getDomainModel() != null) {
            writeValue(viewModelContext, renderTarget, sheet, dmrToResolve);
        }

        return 1;
    } catch (final DatabindingFailedException ex) {
        reportService.report(new EMFFormsSpreadsheetReport(ex, EMFFormsSpreadsheetReport.ERROR));
    } catch (final NoLabelFoundException ex) {
        reportService.report(new EMFFormsSpreadsheetReport(ex, EMFFormsSpreadsheetReport.ERROR));
    } catch (final IOException ex) {
        reportService.report(new EMFFormsSpreadsheetReport(ex, EMFFormsSpreadsheetReport.ERROR));
    } catch (final EMFFormsConverterException ex) {
        reportService.report(new EMFFormsSpreadsheetReport(ex, EMFFormsSpreadsheetReport.ERROR));
    }

    return 0;
}