Example usage for org.apache.poi.ss.usermodel Cell getBooleanCellValue

List of usage examples for org.apache.poi.ss.usermodel Cell getBooleanCellValue

Introduction

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

Prototype

boolean getBooleanCellValue();

Source Link

Document

Get the value of the cell as a boolean.

Usage

From source file:org.opencrx.kernel.portal.wizard.ImportPropertiesFromXlsController.java

License:BSD License

/**
 * Update product configuration type./*w ww  .ja v  a  2s  .  co m*/
 * 
 * @param productConfigurationType
 * @param valueMap
 * @return
 */
public boolean updateProductConfigurationType(ProductConfigurationType productConfigurationType,
        Map<String, Cell> valueMap) {
    PersistenceManager pm = JDOHelper.getPersistenceManager(productConfigurationType);
    Cell cell = null;
    boolean updated = false;
    try {
        // validFrom
        pm.currentTransaction().begin();
        if (valueMap.get(ATTR_PRODUCTCONFIGURATIONTYPE_VALIDFROM) != null) {
            cell = valueMap.get(ATTR_PRODUCTCONFIGURATIONTYPE_VALIDFROM);
            if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC && HSSFDateUtil.isCellDateFormatted(cell)) {
                productConfigurationType.setValidFrom(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                updated = true;
            }
        }
        pm.currentTransaction().commit();
    } catch (Exception e) {
        new ServiceException(e).log();
        try {
            pm.currentTransaction().rollback();
        } catch (Exception e1) {
        }
    }
    try {
        // validTo
        pm.currentTransaction().begin();
        if (valueMap.get(ATTR_PRODUCTCONFIGURATIONTYPE_VALIDTO) != null) {
            cell = valueMap.get(ATTR_PRODUCTCONFIGURATIONTYPE_VALIDTO);
            if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC && HSSFDateUtil.isCellDateFormatted(cell)) {
                productConfigurationType.setValidTo(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                updated = true;
            }
        }
        pm.currentTransaction().commit();
    } catch (Exception e) {
        new ServiceException(e).log();
        try {
            pm.currentTransaction().rollback();
        } catch (Exception e1) {
        }
    }
    try {
        // isDefault
        pm.currentTransaction().begin();
        if (valueMap.get(ATTR_PRODUCTCONFIGURATIONTYPE_ISDEFAULT) != null) {
            cell = valueMap.get(ATTR_PRODUCTCONFIGURATIONTYPE_ISDEFAULT);
            if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
                productConfigurationType.setDefault(new Boolean(cell.getBooleanCellValue()));
                updated = true;
            }
        }
        pm.currentTransaction().commit();
    } catch (Exception e) {
        new ServiceException(e).log();
        try {
            pm.currentTransaction().rollback();
        } catch (Exception e1) {
        }
    }

    return updated;
}

From source file:org.openelis.bean.DataViewBean.java

License:Open Source License

private boolean isSameDataInRows(Row currRow, Row prevRow) {
    int prevType, currType;
    Cell prevCell, currCell;

    if (currRow == null || prevRow == null)
        return false;

    for (int i = 0; i < prevRow.getPhysicalNumberOfCells(); i++) {
        prevCell = prevRow.getCell(i);//  w w w. j  av  a  2  s  . c o m
        currCell = currRow.getCell(i);

        if (prevCell == null) {
            if (currCell == null)
                continue;
            else
                return false;
        } else if (currCell == null) {
            return false;
        }

        prevType = prevCell.getCellType();
        currType = currCell.getCellType();

        if (prevType != currType)
            return false;

        switch (prevType) {
        case Cell.CELL_TYPE_STRING:
            if (!DataBaseUtil.isSame(prevCell.getStringCellValue(), currCell.getStringCellValue()))
                return false;
            break;
        case Cell.CELL_TYPE_NUMERIC:
            if (!DataBaseUtil.isSame(prevCell.getNumericCellValue(), currCell.getNumericCellValue()))
                return false;
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            if (!DataBaseUtil.isSame(prevCell.getBooleanCellValue(), currCell.getBooleanCellValue()))
                return false;
            break;
        }
    }

    return true;
}

From source file:org.openepics.discs.ccdb.core.util.ExcelCell.java

License:Open Source License

/**
 * Creating a String from Excel file cell. If cell contains numeric value, this value is cast to String.
 * If there is no value for this cell, null is returned.
 *
 * @param cell the Excel {@link Cell}//from  w  ww .  jav  a 2 s . co m
 * @param workbook the Excel {@link Workbook}
 *
 * @return the {@link String} result
 */
public static String asStringOrNull(@Nullable Cell cell, Workbook workbook) {
    final String stringValue;
    if (cell != null) {
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            final double numericCellValue = cell.getNumericCellValue();
            if (numericCellValue == (int) numericCellValue) {
                stringValue = String.valueOf((int) numericCellValue);
            } else {
                stringValue = String.valueOf(numericCellValue);
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            stringValue = cell.getStringCellValue() != null ? cell.getStringCellValue() : null;
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            stringValue = null;
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            stringValue = String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            final FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            final CellValue cellValue = evaluator.evaluate(cell);
            if (cellValue != null) {
                final String columnValue = cellValue.getStringValue();
                if (columnValue == null) {
                    stringValue = Double.toString(cellValue.getNumberValue());
                } else {
                    stringValue = columnValue;
                }
            } else {
                stringValue = null;
            }
        } else {
            throw new UnhandledCaseException();
        }
    } else {
        stringValue = null;
    }
    return stringValue;
}

From source file:org.openmrs.module.spreadsheetimport.SpreadsheetImportUtil.java

License:Open Source License

public static File importTemplate(SpreadsheetImportTemplate template, MultipartFile file, String sheetName,
        List<String> messages, boolean rollbackTransaction) throws Exception {

    if (file.isEmpty()) {
        messages.add("file must not be empty");
        return null;
    }/*from   ww  w.jav  a 2  s. com*/

    // Open file
    Workbook wb = WorkbookFactory.create(file.getInputStream());
    Sheet sheet;
    if (!StringUtils.hasText(sheetName)) {
        sheet = wb.getSheetAt(0);
    } else {
        sheet = wb.getSheet(sheetName);
    }

    // Header row
    Row firstRow = sheet.getRow(0);
    if (firstRow == null) {
        messages.add("Spreadsheet header row must not be null");
        return null;
    }

    List<String> columnNames = new Vector<String>();
    for (Cell cell : firstRow) {
        columnNames.add(cell.getStringCellValue());
    }
    if (log.isDebugEnabled()) {
        log.debug("Column names: " + columnNames.toString());
    }

    // Required column names
    List<String> columnNamesOnlyInTemplate = new Vector<String>();
    columnNamesOnlyInTemplate.addAll(template.getColumnNamesAsList());
    columnNamesOnlyInTemplate.removeAll(columnNames);
    if (columnNamesOnlyInTemplate.isEmpty() == false) {
        messages.add("required column names not present: " + toString(columnNamesOnlyInTemplate));
        return null;
    }

    // Extra column names?
    List<String> columnNamesOnlyInSheet = new Vector<String>();
    columnNamesOnlyInSheet.addAll(columnNames);
    columnNamesOnlyInSheet.removeAll(template.getColumnNamesAsList());
    if (columnNamesOnlyInSheet.isEmpty() == false) {
        messages.add(
                "Extra column names present, these will not be processed: " + toString(columnNamesOnlyInSheet));
    }

    // Process rows
    boolean skipThisRow = true;
    for (Row row : sheet) {
        if (skipThisRow == true) {
            skipThisRow = false;
        } else {
            boolean rowHasData = false;
            Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData = template
                    .getMapOfUniqueImportToColumnSetSortedByImportIdx();

            for (UniqueImport uniqueImport : rowData.keySet()) {
                Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
                for (SpreadsheetImportTemplateColumn column : columnSet) {

                    int idx = columnNames.indexOf(column.getName());
                    Cell cell = row.getCell(idx);

                    Object value = null;
                    // check for empty cell (new Encounter)
                    if (cell == null) {
                        rowHasData = true;
                        column.setValue("");
                        continue;
                    }

                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_BOOLEAN:
                        value = new Boolean(cell.getBooleanCellValue());
                        break;
                    case Cell.CELL_TYPE_ERROR:
                        value = new Byte(cell.getErrorCellValue());
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                    case Cell.CELL_TYPE_NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            java.util.Date date = cell.getDateCellValue();
                            value = "'" + new java.sql.Timestamp(date.getTime()).toString() + "'";
                        } else {
                            value = cell.getNumericCellValue();
                        }
                        break;
                    case Cell.CELL_TYPE_STRING:
                        // Escape for SQL
                        value = "'" + cell.getRichStringCellValue() + "'";
                        break;
                    }
                    if (value != null) {
                        rowHasData = true;
                        column.setValue(value);
                    } else
                        column.setValue("");
                }
            }

            for (UniqueImport uniqueImport : rowData.keySet()) {
                Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
                boolean isFirst = true;
                for (SpreadsheetImportTemplateColumn column : columnSet) {

                    if (isFirst) {
                        // Should be same for all columns in unique import
                        //                     System.out.println("SpreadsheetImportUtil.importTemplate: column.getColumnPrespecifiedValues(): " + column.getColumnPrespecifiedValues().size());
                        if (column.getColumnPrespecifiedValues().size() > 0) {
                            Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = column
                                    .getColumnPrespecifiedValues();
                            for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) {
                                //                           System.out.println(columnPrespecifiedValue.getPrespecifiedValue().getValue());
                            }
                        }
                    }
                }
            }

            if (rowHasData) {
                Exception exception = null;
                try {
                    DatabaseBackend.validateData(rowData);
                    String encounterId = DatabaseBackend.importData(rowData, rollbackTransaction);
                    if (encounterId != null) {
                        for (UniqueImport uniqueImport : rowData.keySet()) {
                            Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
                            for (SpreadsheetImportTemplateColumn column : columnSet) {
                                if ("encounter".equals(column.getTableName())) {
                                    int idx = columnNames.indexOf(column.getName());
                                    Cell cell = row.getCell(idx);
                                    if (cell == null)
                                        cell = row.createCell(idx);
                                    cell.setCellValue(encounterId);
                                }
                            }
                        }
                    }
                } catch (SpreadsheetImportTemplateValidationException e) {
                    messages.add("Validation failed: " + e.getMessage());
                    return null;
                } catch (SpreadsheetImportDuplicateValueException e) {
                    messages.add("found duplicate value for column " + e.getColumn().getName() + " with value "
                            + e.getColumn().getValue());
                    return null;
                } catch (SpreadsheetImportSQLSyntaxException e) {
                    messages.add("SQL syntax error: \"" + e.getSqlErrorMessage()
                            + "\".<br/>Attempted SQL Statement: \"" + e.getSqlStatement() + "\"");
                    return null;
                } catch (Exception e) {
                    exception = e;
                }
                if (exception != null) {
                    throw exception;
                }
            }
        }
    }

    // write back Excel file to a temp location
    File returnFile = File.createTempFile("sim", ".xls");
    FileOutputStream fos = new FileOutputStream(returnFile);
    wb.write(fos);
    fos.close();

    return returnFile;
}

From source file:org.openpythia.utilities.SSUtilities.java

License:Apache License

public static Row copyRow(Sheet sheet, Row sourceRow, int destination) {
    Row newRow = sheet.createRow(destination);
    // get the last row from the headings
    int lastCol = sheet.getRow(0).getLastCellNum();
    for (int currentCol = 0; currentCol <= lastCol; currentCol++) {
        Cell newCell = newRow.createCell(currentCol);

        // if there is a cell in the template, copy its content and style
        Cell currentCell = sourceRow.getCell(currentCol);
        if (currentCell != null) {
            newCell.setCellStyle(currentCell.getCellStyle());
            newCell.setCellComment(currentCell.getCellComment());
            switch (currentCell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                newCell.setCellValue(currentCell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_NUMERIC:
                newCell.setCellValue(currentCell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                String dummy = currentCell.getCellFormula();
                dummy = dummy.replace("Row", String.valueOf(destination + 1));
                newCell.setCellFormula(dummy);
                newCell.setCellFormula(/*from   w  w w. jav  a  2 s  . c o  m*/
                        currentCell.getCellFormula().replace("Row", String.valueOf(destination + 1)));
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                newCell.setCellValue(currentCell.getBooleanCellValue());
                break;
            default:
            }
        }
    }

    // if the row contains merged regions, copy them to the new row
    int numberMergedRegions = sheet.getNumMergedRegions();
    for (int i = 0; i < numberMergedRegions; i++) {
        CellRangeAddress mergedRegion = sheet.getMergedRegion(i);

        if (mergedRegion.getFirstRow() == sourceRow.getRowNum()
                && mergedRegion.getLastRow() == sourceRow.getRowNum()) {
            // this region is within the row - so copy it
            sheet.addMergedRegion(new CellRangeAddress(destination, destination, mergedRegion.getFirstColumn(),
                    mergedRegion.getLastColumn()));
        }
    }

    return newRow;
}

From source file:org.openstreetmap.josm.plugins.opendata.core.io.tabular.XlsReader.java

License:GNU General Public License

@Override
protected String[] readLine(ProgressMonitor progressMonitor) throws IOException {
    if (sheet != null) {
        Row row = sheet.getRow(rowIndex++);
        if (row != null) {
            List<String> result = new ArrayList<>();
            for (Cell cell : row) {
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    result.add(cell.getRichStringCellValue().getString());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        result.add(cell.getDateCellValue().toString());
                    } else {
                        result.add(Double.toString(cell.getNumericCellValue()));
                    }//w  w w .  j a va  2s. c om
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    result.add(Boolean.toString(cell.getBooleanCellValue()));
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    result.add(cell.getCellFormula());
                    break;
                default:
                    result.add("");
                }
            }
            return result.toArray(new String[0]);
        }
    }
    return null;
}

From source file:org.pentaho.reporting.ui.datasources.table.ImportFromFileTask.java

License:Open Source License

private void importFromFile(final File file, final boolean firstRowIsHeader) {
    final ByteArrayOutputStream bout = new ByteArrayOutputStream(Math.max(8192, (int) file.length()));
    try {/* www  .j  a v  a2s  . co m*/
        final InputStream fin = new FileInputStream(file);
        try {
            IOUtils.getInstance().copyStreams(new BufferedInputStream(fin), bout);
        } finally {
            fin.close();
        }

        if (Thread.currentThread().isInterrupted()) {
            return;
        }

        final Workbook workbook = WorkbookFactory.create(new ByteArrayInputStream(bout.toByteArray()));
        int sheetIndex = 0;
        if (workbook.getNumberOfSheets() > 1) {
            final SheetSelectorDialog selectorDialog = new SheetSelectorDialog(workbook, parent);
            if (selectorDialog.performSelection()) {
                sheetIndex = selectorDialog.getSelectedIndex();
            } else {
                return;
            }
        }

        final TypedTableModel tableModel = new TypedTableModel();
        final Sheet sheet = workbook.getSheetAt(sheetIndex);
        final Iterator rowIterator = sheet.rowIterator();

        if (firstRowIsHeader) {
            if (rowIterator.hasNext()) {
                final Row headerRow = (Row) rowIterator.next();
                final short cellCount = headerRow.getLastCellNum();
                for (short colIdx = 0; colIdx < cellCount; colIdx++) {
                    final Cell cell = headerRow.getCell(colIdx);
                    if (cell != null) {
                        while (colIdx > tableModel.getColumnCount()) {
                            tableModel.addColumn(Messages.getString("TableDataSourceEditor.Column",
                                    String.valueOf(tableModel.getColumnCount())), Object.class);
                        }

                        final RichTextString string = cell.getRichStringCellValue();
                        if (string != null) {
                            tableModel.addColumn(string.getString(), Object.class);
                        } else {
                            tableModel.addColumn(
                                    Messages.getString("TableDataSourceEditor.Column", String.valueOf(colIdx)),
                                    Object.class);
                        }
                    }
                }
            }
        }

        Object[] rowData = null;
        while (rowIterator.hasNext()) {
            final Row row = (Row) rowIterator.next();
            final short cellCount = row.getLastCellNum();
            if (cellCount == -1) {
                continue;
            }
            if (rowData == null || rowData.length != cellCount) {
                rowData = new Object[cellCount];
            }

            for (short colIdx = 0; colIdx < cellCount; colIdx++) {
                final Cell cell = row.getCell(colIdx);

                final Object value;
                if (cell != null) {
                    if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                        final RichTextString string = cell.getRichStringCellValue();
                        if (string != null) {
                            value = string.getString();
                        } else {
                            value = null;
                        }
                    } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                        final CellStyle hssfCellStyle = cell.getCellStyle();
                        final short dataFormat = hssfCellStyle.getDataFormat();
                        final String dataFormatString = hssfCellStyle.getDataFormatString();
                        if (isDateFormat(dataFormat, dataFormatString)) {
                            value = cell.getDateCellValue();
                        } else {
                            value = cell.getNumericCellValue();
                        }
                    } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
                        value = cell.getBooleanCellValue();
                    } else {
                        value = cell.getStringCellValue();
                    }
                } else {
                    value = null;
                }

                if (value != null && "".equals(value) == false) {
                    while (colIdx >= tableModel.getColumnCount()) {
                        tableModel.addColumn(Messages.getString("TableDataSourceEditor.Column",
                                String.valueOf(tableModel.getColumnCount())), Object.class);
                    }
                }

                rowData[colIdx] = value;
            }

            if (Thread.currentThread().isInterrupted()) {
                return;
            }

            tableModel.addRow(rowData);
        }

        final int colCount = tableModel.getColumnCount();
        final int rowCount = tableModel.getRowCount();
        for (int col = 0; col < colCount; col++) {
            Class type = null;
            for (int row = 0; row < rowCount; row += 1) {
                final Object value = tableModel.getValueAt(row, col);
                if (value == null) {
                    continue;
                }
                if (type == null) {
                    type = value.getClass();
                } else if (type != Object.class) {
                    if (type.isInstance(value) == false) {
                        type = Object.class;
                    }
                }
            }

            if (Thread.currentThread().isInterrupted()) {
                return;
            }

            if (type != null) {
                tableModel.setColumnType(col, type);
            }
        }

        parent.importComplete(tableModel);
    } catch (Exception e) {
        parent.importFailed(e);
        logger.error("Failed to import spreadsheet", e); // NON-NLS
    }
}

From source file:org.projectforge.excel.ExportSheet.java

License:Open Source License

private static Row copyRow(Sheet worksheet, int rowNum) {
    Row sourceRow = worksheet.getRow(rowNum);

    //Save the text of any formula before they are altered by row shifting
    String[] formulasArray = new String[sourceRow.getLastCellNum()];
    for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
        if (sourceRow.getCell(i) != null && sourceRow.getCell(i).getCellType() == Cell.CELL_TYPE_FORMULA)
            formulasArray[i] = sourceRow.getCell(i).getCellFormula();
    }/* w w w . ja va 2  s  .  c o  m*/

    worksheet.shiftRows(rowNum, worksheet.getLastRowNum(), 1);
    Row newRow = sourceRow; //Now sourceRow is the empty line, so let's rename it
    sourceRow = worksheet.getRow(rowNum + 1); //Now the source row is at rowNum+1

    // Loop through source columns to add to new row
    for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
        // Grab a copy of the old/new cell
        Cell oldCell = sourceRow.getCell(i);
        Cell newCell;

        // If the old cell is null jump to next cell
        if (oldCell == null) {
            continue;
        } else {
            newCell = newRow.createCell(i);
        }

        // Copy style from old cell and apply to new cell
        CellStyle newCellStyle = worksheet.getWorkbook().createCellStyle();
        newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
        newCell.setCellStyle(newCellStyle);

        // If there is a cell comment, copy
        if (oldCell.getCellComment() != null) {
            newCell.setCellComment(oldCell.getCellComment());
        }

        // If there is a cell hyperlink, copy
        if (oldCell.getHyperlink() != null) {
            newCell.setHyperlink(oldCell.getHyperlink());
        }

        // Set the cell data type
        newCell.setCellType(oldCell.getCellType());

        // Set the cell data value
        switch (oldCell.getCellType()) {
        case Cell.CELL_TYPE_BLANK:
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            newCell.setCellValue(oldCell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_ERROR:
            newCell.setCellErrorValue(oldCell.getErrorCellValue());
            break;
        case Cell.CELL_TYPE_FORMULA:
            newCell.setCellFormula(formulasArray[i]);
            break;
        case Cell.CELL_TYPE_NUMERIC:
            newCell.setCellValue(oldCell.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING:
            newCell.setCellValue(oldCell.getRichStringCellValue());
            break;
        default:
            break;
        }
    }

    // If there are any merged regions in the source row, copy to new row
    for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {
        CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
        if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {
            CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),
                    (newRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())),
                    cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
            worksheet.addMergedRegion(newCellRangeAddress);
        }
    }
    return newRow;
}

From source file:org.ramadda.data.docs.TabularOutputHandler.java

License:Apache License

/**
 * _more_//from   w ww  .  ja va2  s . co m
 *
 * @param request _more_
 * @param entry _more_
 * @param suffix _more_
 * @param inputStream _more_
 * @param visitInfo _more_
 * @param visitor _more_
 *
 * @throws Exception _more_
 */
private void visitXls(Request request, Entry entry, String suffix, InputStream inputStream,
        TextReader visitInfo, TabularVisitor visitor) throws Exception {
    //        System.err.println("visitXls: making workbook");
    Workbook wb = makeWorkbook(suffix, inputStream);
    //        System.err.println("visitXls:" + visitInfo.getSkip() + " max rows:" + visitInfo.getMaxRows()+ " #sheets:" + wb.getNumberOfSheets());
    int maxRows = visitInfo.getMaxRows();
    for (int sheetIdx = 0; sheetIdx < wb.getNumberOfSheets(); sheetIdx++) {
        if (!visitInfo.okToShowSheet(sheetIdx)) {
            continue;
        }
        Sheet sheet = wb.getSheetAt(sheetIdx);
        //            System.err.println("\tsheet:" + sheet.getSheetName() + " #rows:" + sheet.getLastRowNum());
        List<List<Object>> rows = new ArrayList<List<Object>>();
        int sheetSkip = visitInfo.getSkip();
        for (int rowIdx = sheet.getFirstRowNum(); (rows.size() < maxRows)
                && (rowIdx <= sheet.getLastRowNum()); rowIdx++) {
            if (sheetSkip-- > 0) {
                continue;
            }

            Row row = sheet.getRow(rowIdx);
            if (row == null) {
                continue;
            }
            List<Object> cols = new ArrayList<Object>();
            short firstCol = row.getFirstCellNum();
            for (short col = firstCol; (col < MAX_COLS) && (col < row.getLastCellNum()); col++) {
                Cell cell = row.getCell(col);
                if (cell == null) {
                    break;
                }
                Object value = null;
                int type = cell.getCellType();
                if (type == cell.CELL_TYPE_NUMERIC) {
                    value = new Double(cell.getNumericCellValue());
                } else if (type == cell.CELL_TYPE_BOOLEAN) {
                    value = new Boolean(cell.getBooleanCellValue());
                } else if (type == cell.CELL_TYPE_ERROR) {
                    value = "" + cell.getErrorCellValue();
                } else if (type == cell.CELL_TYPE_BLANK) {
                    value = "";
                } else if (type == cell.CELL_TYPE_FORMULA) {
                    value = cell.getCellFormula();
                } else {
                    value = cell.getStringCellValue();
                }
                cols.add(value);
            }

            /**
             * ** TODO
             * org.ramadda.util.text.Row row = new Row(cols);
             *
             * if ( !visitInfo.rowOk(row)) {
             *   if (rows.size() == 0) {
             *       //todo: check for the header line
             *   } else {
             *       continue;
             *   }
             * }
             */
            rows.add(cols);
        }
        if (!visitor.visit(visitInfo, sheet.getSheetName(), rows)) {
            break;
        }
    }
}

From source file:org.ramadda.data.docs.TabularOutputHandler.java

License:Apache License

/**
 * _more_/*from  w w w.  j av  a  2  s .c  om*/
 *
 * @param args _more_
 *
 * @throws Exception _more_
 */
public static void main(String[] args) throws Exception {
    Workbook wb = makeWorkbook(IOUtil.getFileExtension(args[0]), new FileInputStream(args[0]));
    for (int sheetIdx = 0; sheetIdx < wb.getNumberOfSheets(); sheetIdx++) {
        Sheet sheet = wb.getSheetAt(sheetIdx);
        System.err.println(sheet.getSheetName());
        for (int rowIdx = sheet.getFirstRowNum(); rowIdx <= sheet.getLastRowNum(); rowIdx++) {
            Row row = sheet.getRow(rowIdx);
            if (row == null) {
                continue;
            }
            short firstCol = row.getFirstCellNum();
            int colCnt = 0;
            for (short col = firstCol; col < row.getLastCellNum(); col++) {
                Cell cell = row.getCell(col);
                if (cell == null) {
                    break;
                }
                Object value = null;
                int type = cell.getCellType();
                if (type == cell.CELL_TYPE_NUMERIC) {
                    value = new Double(cell.getNumericCellValue());
                } else if (type == cell.CELL_TYPE_BOOLEAN) {
                    value = new Boolean(cell.getBooleanCellValue());
                } else if (type == cell.CELL_TYPE_ERROR) {
                    value = "" + cell.getErrorCellValue();
                } else if (type == cell.CELL_TYPE_BLANK) {
                    value = "";
                } else if (type == cell.CELL_TYPE_FORMULA) {
                    value = cell.getCellFormula();
                } else {
                    value = cell.getStringCellValue();
                }
                if (colCnt++ > 0)
                    System.out.print(",");
                System.out.print(value);
            }
            System.out.println("");
        }
    }
}