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

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

Introduction

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

Prototype

int getPhysicalNumberOfRows();

Source Link

Document

Returns the number of physically defined rows (NOT the number of rows in the sheet)

Usage

From source file:org.apache.metamodel.excel.DefaultSpreadsheetReaderDelegate.java

License:Apache License

@Override
public DataSet executeQuery(Table table, Column[] columns, int maxRows) {
    final Workbook wb = ExcelUtils.readWorkbook(_resource);
    final Sheet sheet = wb.getSheet(table.getName());

    if (sheet == null || sheet.getPhysicalNumberOfRows() == 0) {
        return new EmptyDataSet(columns);
    }/*from www. java 2 s. c  om*/

    DataSet dataSet = ExcelUtils.getDataSet(wb, sheet, table, _configuration);

    if (maxRows > 0) {
        dataSet = new MaxRowsDataSet(dataSet, maxRows);
    }
    return dataSet;
}

From source file:org.apache.metamodel.excel.DefaultSpreadsheetReaderDelegate.java

License:Apache License

private MutableTable createTable(final Workbook wb, final Sheet sheet) {
    final MutableTable table = new MutableTable(sheet.getSheetName());

    if (sheet.getPhysicalNumberOfRows() <= 0) {
        // no physical rows in sheet
        return table;
    }/*  w w w.ja v  a 2s . co m*/

    final Iterator<Row> rowIterator = ExcelUtils.getRowIterator(sheet, _configuration, false);

    if (!rowIterator.hasNext()) {
        // no physical rows in sheet
        return table;
    }

    Row row = null;

    if (_configuration.isSkipEmptyLines()) {
        while (row == null && rowIterator.hasNext()) {
            row = rowIterator.next();
        }
    } else {
        row = rowIterator.next();
    }

    final int columnNameLineNumber = _configuration.getColumnNameLineNumber();
    if (columnNameLineNumber == ExcelConfiguration.NO_COLUMN_NAME_LINE) {

        // get to the first non-empty line (no matter if lines are skipped
        // or not we need to read ahead to figure out how many columns there
        // are!)
        while (row == null && rowIterator.hasNext()) {
            row = rowIterator.next();
        }

        // build columns without any intrinsic column names
        final ColumnNamingStrategy columnNamingStrategy = _configuration.getColumnNamingStrategy();
        try (final ColumnNamingSession columnNamingSession = columnNamingStrategy.startColumnNamingSession()) {
            final int offset = getColumnOffset(row);
            for (int i = 0; i < offset; i++) {
                columnNamingSession.getNextColumnName(new ColumnNamingContextImpl(i));
            }

            for (int j = offset; j < row.getLastCellNum(); j++) {
                final ColumnNamingContext namingContext = new ColumnNamingContextImpl(table, null, j);
                final Column column = new MutableColumn(columnNamingSession.getNextColumnName(namingContext),
                        ColumnType.STRING, table, j, true);
                table.addColumn(column);
            }
        }

    } else {

        boolean hasColumns = true;

        // iterate to the column name line number (if above 1)
        for (int j = 1; j < columnNameLineNumber; j++) {
            if (rowIterator.hasNext()) {
                row = rowIterator.next();
            } else {
                hasColumns = false;
                break;
            }
        }

        if (hasColumns) {
            createColumns(table, wb, row);
        }
    }

    return table;
}

From source file:org.corpus_tools.peppermodules.spreadsheet.Spreadsheet2SaltMapper.java

License:Apache License

/**
 * Add annotations to the salt graph//from w w w .  ja v a  2  s . com
 * 
 * @param annoPrimRelations
 * @param corpusSheet
 * @param mergedCells
 * @param layerTierCouples
 * @param progressProcessedNumberOfColumns
 */
private void setAnnotations(HashMap<Integer, Integer> annoPrimRelations, Sheet corpusSheet,
        Table<Integer, Integer, CellRangeAddress> mergedCells, Map<String, SLayer> layerTierCouples,
        int progressProcessedNumberOfColumns) {
    if (!annoPrimRelations.isEmpty()) {
        Row headerRow = corpusSheet.getRow(0);
        DataFormatter formatter = new DataFormatter();
        int progressTotalNumberOfColumns = annoPrimRelations.keySet().size();
        for (int annoTier : annoPrimRelations.keySet()) {

            SSpan annoSpan = null;
            int currAnno = 1;

            while (currAnno < corpusSheet.getPhysicalNumberOfRows()) {
                String annoName = headerRow.getCell(annoTier).toString();
                Row row = corpusSheet.getRow(currAnno);
                Cell annoCell = row.getCell(annoTier);

                if (annoCell != null && !annoCell.toString().isEmpty()) {
                    String annoText = "";
                    annoText = formatter.formatCellValue(annoCell);

                    int annoStart = currAnno - 1;
                    int annoEnd = getLastCell(annoCell, mergedCells);
                    DataSourceSequence<Integer> sequence = new DataSourceSequence<Integer>();
                    sequence.setStart(annoStart);
                    sequence.setEnd(annoEnd);
                    sequence.setDataSource(getDocument().getDocumentGraph().getTimeline());

                    List<SToken> sTokens = getDocument().getDocumentGraph().getTokensBySequence(sequence);

                    List<SToken> tokenOfSpan = new ArrayList<>();

                    if (sTokens == null) {
                        SpreadsheetImporter.logger.error("Segmentation error: The segmentation of the tier \""
                                + headerRow.getCell(annoTier).toString() + "\" in the document: \""
                                + getResourceURI().lastSegment() + "\" in line: " + currAnno
                                + " does not match to its primary text: \""
                                + headerRow.getCell(annoPrimRelations.get(annoTier)).toString() + "\".");
                    } else {
                        for (SToken tok : sTokens) {
                            STextualDS textualDS = getTextualDSForNode(tok, getDocument().getDocumentGraph());
                            if (textualDS.getName()
                                    .equals(headerRow.getCell(annoPrimRelations.get(annoTier)).toString())) {
                                tokenOfSpan.add(tok);
                            }
                        }
                    }

                    annoSpan = getDocument().getDocumentGraph().createSpan(tokenOfSpan);

                    if (annoSpan != null && annoName != null && !annoName.isEmpty()) {
                        // remove primary text info of annotation if given
                        if (annoName.matches(".+\\[.+\\]")) {
                            annoName = annoName.split("\\[")[0];
                        }
                        annoSpan.createAnnotation(null, annoName, annoText);
                        annoSpan.setName(annoName);
                    }
                }

                if (getProps().getLayer() != null && annoSpan != null) {

                    if (layerTierCouples.size() > 0) {
                        if (layerTierCouples.get(annoName) != null) {
                            SLayer sLayer = layerTierCouples.get(annoName);
                            getDocument().getDocumentGraph().addLayer(sLayer);
                            sLayer.addNode(annoSpan);
                        }
                    }
                }
                currAnno++;
            } // end for each row of annotation

            progressProcessedNumberOfColumns++;
            setProgress((double) progressProcessedNumberOfColumns / (double) progressTotalNumberOfColumns);
        } // end for each annotation layer
    } else {
        SpreadsheetImporter.logger.warn("No annotations except for primary texts found in document \""
                + getResourceURI().lastSegment() + "\".");
    }
}

From source file:org.corpus_tools.peppermodules.spreadsheet.Spreadsheet2SaltMapper.java

License:Apache License

/**
 * Set the primary text of each document
 * //from   w  w w  .  jav  a2s.  c  o m
 * @param column
 * @param primText
 * @param corpusSheet
 * @param primTextPos
 * @param annoPrimRelations
 * @param mergedCells
 * @param layerTierCouples
 * @return
 */
private int setPrimText(Sheet corpusSheet, List<Integer> primTextPos,
        HashMap<Integer, Integer> annoPrimRelations, Row headerRow,
        Table<Integer, Integer, CellRangeAddress> mergedCells, Map<String, SLayer> layerTierCouples) {
    // initialize with number of token we have to create
    int progressTotalNumberOfColumns = primTextPos.size();
    // add each annotation to this number

    int progressProcessedNumberOfColumns = 0;

    // use formater to ensure that e.g. integers will not be converted into
    // decimals
    DataFormatter formatter = new DataFormatter();
    // save all tokens of the current primary text
    List<SToken> currentTokList = new ArrayList<>();
    // save all tokens of the current primary text
    for (int primText : primTextPos) {

        // initialize primaryText
        STextualDS primaryText = SaltFactory.createSTextualDS();
        StringBuilder currentText = new StringBuilder();

        if (headerRow.getCell(primText) != null) {
            primaryText.setName(headerRow.getCell(primText).toString());
        }
        getDocument().getDocumentGraph().addNode(primaryText);

        int offset = currentText.length();

        SToken lastTok = null;

        // start with the second row of the table, since the first row holds
        // the name of each tier
        int currRow = 1;
        while (currRow < corpusSheet.getPhysicalNumberOfRows()) {
            // iterate through all rows of the given corpus sheet

            Row row = corpusSheet.getRow(currRow);
            Cell primCell = row.getCell(primText);
            SToken currTok = null;
            int endCell = currRow;

            String text = null;
            if (primCell != null && !primCell.toString().isEmpty()) {
                text = formatter.formatCellValue(primCell);

            } else if (getProps().getIncludeEmptyPrimCells()) {
                text = "";

            }
            if (text != null) {
                int start = offset;
                int end = start + text.length();
                offset += text.length();
                currentText.append(text);

                currTok = getDocument().getDocumentGraph().createToken(primaryText, start, end);

                if (primCell != null) {
                    endCell = getLastCell(primCell, mergedCells);
                }
            }

            if (currTok != null) {
                if (lastTok != null && getProps().getAddOrderRelation()) {
                    addOrderRelation(lastTok, currTok, headerRow.getCell(primText).toString());
                }
                // add timeline relation
                addTimelineRelation(currTok, currRow, endCell, corpusSheet);

                // remember all SToken
                currentTokList.add(currTok);

                // insert space between tokens
                if (text != null && (currRow != corpusSheet.getLastRowNum())) {
                    currentText.append(" ");
                    offset++;
                }
            }

            if (currTok != null) {
                lastTok = currTok;
            }
            currRow++;
        } // end for each token row
        primaryText.setText(currentText.toString());

        progressProcessedNumberOfColumns++;
        setProgress((double) progressProcessedNumberOfColumns / (double) progressTotalNumberOfColumns);

        if (getProps().getLayer() != null) {
            if (currentTokList != null && layerTierCouples.size() > 0) {
                if (layerTierCouples.get(primaryText.getName()) != null) {
                    SLayer sLayer = layerTierCouples.get(primaryText.getName());
                    getDocument().getDocumentGraph().addLayer(sLayer);
                    for (SToken t : currentTokList) {
                        sLayer.addNode(t);
                    }
                }
            }
        }
    } // end for each primTextPos
    return progressProcessedNumberOfColumns;
}

From source file:org.corpus_tools.peppermodules.spreadsheet.Spreadsheet2SaltMapper.java

License:Apache License

private void setDocMetaData(Workbook workbook) {
    Sheet metaSheet = null;

    // default ("Tabelle2"/ second sheet)
    if (getProps().getMetaSheet().equals("Tabelle2")) {
        if (workbook.getNumberOfSheets() > 1) {
            metaSheet = workbook.getSheetAt(1);
        }//from   www .ja  v  a  2 s . c o  m
    } else {
        // get corpus sheet by name
        metaSheet = workbook.getSheet(getProps().getCorpusSheet());
    }

    if (metaSheet != null) {
        DataFormatter formatter = new DataFormatter();
        // start with the second row of the table, since the first row holds
        // the name of each tier
        int currRow = 1;
        while (currRow < metaSheet.getPhysicalNumberOfRows()) {
            // iterate through all rows of the given meta informations

            Row row = metaSheet.getRow(currRow);
            Cell metaKey = row.getCell(0);
            Cell metaValue = row.getCell(1);

            if (metaKey != null && !metaKey.toString().isEmpty()) {
                if (metaValue != null && !metaValue.toString().isEmpty()) {
                    if (getDocument().getMetaAnnotation(metaKey.toString()) == null) {
                        getDocument().createMetaAnnotation(null, formatter.formatCellValue(metaKey),
                                formatter.formatCellValue(metaValue));
                    } else {
                        SpreadsheetImporter.logger
                                .warn("A meta information with the name \"" + formatter.formatCellValue(metaKey)
                                        + "\" allready exists and will not be replaced.");
                    }
                } else {
                    SpreadsheetImporter.logger
                            .warn("No value for the meta data: \"" + metaKey.toString() + "\" found.");
                }
            } else {
                if (metaValue != null && !metaValue.toString().isEmpty()) {
                    SpreadsheetImporter.logger.warn(
                            "No meta annotation name for the value \"" + metaValue.toString() + "\" found.");
                }
            }
            currRow++;
        }
    }
}

From source file:org.cytoscape.tableimport.internal.ui.PreviewTablePanel.java

License:Open Source License

/**
 * Load file and show preview.//www.j  a  v  a  2  s .  c om
 */
public void updatePreviewTable(final Workbook workbook, final String fileType, final String fileFullName,
        final InputStream tempIs, final List<String> delimiters, final String commentLineChar,
        final int startLine) throws IOException {
    if (tempIs == null)
        return;

    if ((commentLineChar != null) && (commentLineChar.trim().length() != 0))
        this.commentChar = commentLineChar;
    else
        this.commentChar = null;

    this.startLine = startLine;

    updating = true;

    try {
        getSheetComboBox().removeAllItems();
        getSheetComboBox().setVisible(false);
        sheetLabel.setVisible(false);

        PreviewTableModel newModel = null;

        if (SupportedFileType.EXCEL.getExtension().equalsIgnoreCase(fileType)
                || SupportedFileType.OOXML.getExtension().equalsIgnoreCase(fileType)) {
            final int numberOfSheets = workbook.getNumberOfSheets();

            if (numberOfSheets == 0)
                throw new IllegalStateException("No sheet found in the workbook.");

            for (int i = 0; i < numberOfSheets; i++) {
                final Sheet sheet = workbook.getSheetAt(i);

                if (sheet.getPhysicalNumberOfRows() > 0)
                    getSheetComboBox().addItem(sheet);
            }

            if (getSheetComboBox().getItemCount() > 0)
                getSheetComboBox().setSelectedIndex(0);

            if (getSheetComboBox().getItemCount() > 1) {
                sheetLabel.setVisible(true);
                getSheetComboBox().setVisible(true);
            }

            /*
             * Load each sheet in the workbook.
             */
            if (getSheetComboBox().getItemCount() > 0) {
                final Sheet sheet = workbook.getSheetAt(0);
                updatePreviewTable(sheet);
            } else {
                throw new RuntimeException("No data found in the Excel sheets.");
            }
        } else {
            newModel = parseText(tempIs, delimiters, startLine);

            String sourceName;
            String[] urlParts = fileFullName.split("/");

            if (urlParts.length > 0 && !fileFullName.isEmpty())
                sourceName = urlParts[urlParts.length - 1];
            else
                sourceName = "Source Table";

            dataTypes = TypeUtil.guessDataTypes(newModel);
            types = TypeUtil.guessTypes(importType, newModel, dataTypes, null);
            listDelimiters = new String[newModel.getColumnCount()];

            updatePreviewTable(newModel, sourceName);
        }
    } finally {
        updating = false;
    }
}

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/*from  w w  w. j ava 2s. c  om*/
 * @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  . j a  v a  2s.co  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//  w  ww  .j  ava 2 s.c  o m
 * @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.deidentifier.arx.io.ImportAdapterExcel.java

License:Open Source License

/**
 * Creates a new instance of this object with given configuration
 * //from  www.j ava2 s .co m
 * Depending upon the file type it either uses HSSF or XSSF to access the
 * file. In both cases {@link #iterator} will be assigned a reference to
 * an iterator, which can then be used to access the actual data on a row by
 * row basis.
 * 
 * @param config
 *            {@link #config}
 * 
 * @throws IOException
 *             In case file doesn't contain actual data
 */
protected ImportAdapterExcel(ImportConfigurationExcel config) throws IOException {

    super(config);
    this.config = config;

    /* Get row iterator */
    input = new FileInputStream(config.getFileLocation());
    Workbook workbook = null;

    if (config.getExcelFileType() == ExcelFileTypes.XLS) {
        workbook = new HSSFWorkbook(input);
    } else if (config.getExcelFileType() == ExcelFileTypes.XLSX) {
        workbook = new XSSFWorkbook(input);
    } else {
        input.close();
        throw new IllegalArgumentException("File type not supported");
    }

    workbook.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK);
    Sheet sheet = workbook.getSheetAt(config.getSheetIndex());
    iterator = sheet.iterator();

    /* Get total number of rows */
    totalRows = sheet.getPhysicalNumberOfRows();

    /* Check whether there is actual data within the file */
    if (iterator.hasNext()) {

        row = iterator.next();
        if (config.getContainsHeader()) {
            if (!iterator.hasNext()) {
                throw new IOException("File contains nothing but header");
            }
        }
    } else {
        throw new IOException("File contains no data");
    }

    // Create header
    header = createHeader();
}