Example usage for org.apache.poi.hssf.usermodel HSSFCell getRichStringCellValue

List of usage examples for org.apache.poi.hssf.usermodel HSSFCell getRichStringCellValue

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFCell getRichStringCellValue.

Prototype

public HSSFRichTextString getRichStringCellValue() 

Source Link

Document

get the value of the cell as a string - for numeric cells we throw an exception.

Usage

From source file:com.report.excel.ExcelToHtmlConverter.java

License:Apache License

protected boolean processCell(HSSFCell cell, Element tableCellElement, int normalWidthPx, int maxSpannedWidthPx,
        float normalHeightPt) {
    final HSSFCellStyle cellStyle = cell.getCellStyle();

    String value;/*from  ww  w  .j  av a2 s.  c  om*/
    switch (cell.getCellType()) {
    case HSSFCell.CELL_TYPE_STRING:
        // XXX: enrich
        value = cell.getRichStringCellValue().getString();
        break;
    case HSSFCell.CELL_TYPE_FORMULA:
        /*switch (evaluator.evaluateFormulaCell(cell)) {
            case Cell.CELL_TYPE_BOOLEAN:
          value = cell.getBooleanCellValue();
           break;
            case Cell.CELL_TYPE_NUMERIC:
          value = cell.getNumericCellValue();
           break;
            case Cell.CELL_TYPE_STRING:
           System.out.println(cell.getStringCellValue());
           break;
            case Cell.CELL_TYPE_BLANK:
           break;
            case Cell.CELL_TYPE_ERROR:
           System.out.println(cell.getErrorCellValue());
           break;
            case Cell.CELL_TYPE_FORMULA: 
           break;
        }*/

        switch (cell.getCachedFormulaResultType()) {
        case HSSFCell.CELL_TYPE_STRING:
            HSSFRichTextString str = cell.getRichStringCellValue();
            if (str != null && str.length() > 0) {
                value = (str.toString());
            } else {
                value = ExcelToHtmlUtils.EMPTY;
            }
            break;
        case HSSFCell.CELL_TYPE_NUMERIC:
            HSSFCellStyle style = cellStyle;
            if (style == null) {
                value = String.valueOf(cell.getNumericCellValue());
            } else {
                value = (_formatter.formatRawCellContents(cell.getNumericCellValue(), style.getDataFormat(),
                        style.getDataFormatString()));
            }
            break;
        case HSSFCell.CELL_TYPE_BOOLEAN:
            value = String.valueOf(cell.getBooleanCellValue());
            break;
        case HSSFCell.CELL_TYPE_ERROR:
            value = ErrorEval.getText(cell.getErrorCellValue());
            break;
        default:
            logger.log(POILogger.WARN,
                    "Unexpected cell cachedFormulaResultType (" + cell.getCachedFormulaResultType() + ")");
            value = ExcelToHtmlUtils.EMPTY;
            break;
        }
        break;
    case HSSFCell.CELL_TYPE_BLANK:
        value = ExcelToHtmlUtils.EMPTY;
        break;
    case HSSFCell.CELL_TYPE_NUMERIC:
        value = _formatter.formatCellValue(cell);
        break;
    case HSSFCell.CELL_TYPE_BOOLEAN:
        value = String.valueOf(cell.getBooleanCellValue());
        break;
    case HSSFCell.CELL_TYPE_ERROR:
        value = ErrorEval.getText(cell.getErrorCellValue());
        break;
    default:
        logger.log(POILogger.WARN, "Unexpected cell type (" + cell.getCellType() + ")");
        return true;
    }

    final boolean noText = ExcelToHtmlUtils.isEmpty(value);
    final boolean wrapInDivs = !noText && isUseDivsToSpan() && !cellStyle.getWrapText();

    final short cellStyleIndex = cellStyle.getIndex();
    if (cellStyleIndex != 0) {
        HSSFWorkbook workbook = cell.getRow().getSheet().getWorkbook();
        String mainCssClass = getStyleClassName(workbook, cellStyle);
        if (wrapInDivs) {
            tableCellElement.setAttribute("class", mainCssClass + " " + cssClassContainerCell);
        } else {
            tableCellElement.setAttribute("class", mainCssClass);
        }

        if (noText) {
            /*
             * if cell style is defined (like borders, etc.) but cell text
             * is empty, add " " to output, so browser won't collapse
             * and ignore cell
             */
            value = "\u00A0";
        }
    }

    if (isOutputLeadingSpacesAsNonBreaking() && value.startsWith(" ")) {
        StringBuilder builder = new StringBuilder();
        for (int c = 0; c < value.length(); c++) {
            if (value.charAt(c) != ' ')
                break;
            builder.append('\u00a0');
        }

        if (value.length() != builder.length())
            builder.append(value.substring(builder.length()));

        value = builder.toString();
    }

    Text text = htmlDocumentFacade.createText(value);

    if (wrapInDivs) {
        Element outerDiv = htmlDocumentFacade.createBlock();
        outerDiv.setAttribute("class", this.cssClassContainerDiv);

        Element innerDiv = htmlDocumentFacade.createBlock();
        StringBuilder innerDivStyle = new StringBuilder();
        innerDivStyle.append("position:absolute;min-width:");
        innerDivStyle.append(normalWidthPx);
        innerDivStyle.append("px;");
        if (maxSpannedWidthPx != Integer.MAX_VALUE) {
            innerDivStyle.append("max-width:");
            innerDivStyle.append(maxSpannedWidthPx);
            innerDivStyle.append("px;");
        }
        innerDivStyle.append("overflow:hidden;max-height:");
        innerDivStyle.append(normalHeightPt);
        innerDivStyle.append("pt;white-space:nowrap;");
        ExcelToHtmlUtils.appendAlign(innerDivStyle, cellStyle.getAlignment());
        htmlDocumentFacade.addStyleClass(outerDiv, cssClassPrefixDiv, innerDivStyle.toString());

        innerDiv.appendChild(text);
        outerDiv.appendChild(innerDiv);
        tableCellElement.appendChild(outerDiv);
    } else {
        tableCellElement.appendChild(text);
    }

    return ExcelToHtmlUtils.isEmpty(value) && cellStyleIndex == 0;
}

From source file:com.siva.javamultithreading.ExcelUtil.java

public static void copyCell(HSSFWorkbook newWorkbook, HSSFCell oldCell, HSSFCell newCell,
        Map<Integer, HSSFCellStyle> styleMap) {
    if (styleMap != null) {
        int stHashCode = oldCell.getCellStyle().hashCode();
        HSSFCellStyle newCellStyle = styleMap.get(stHashCode);
        if (newCellStyle == null) {
            newCellStyle = newWorkbook.createCellStyle();
            newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
            styleMap.put(stHashCode, newCellStyle);
        }//from  w w  w.j a v a 2 s .  c om
        newCell.setCellStyle(newCellStyle);
    }
    switch (oldCell.getCellType()) {
    case HSSFCell.CELL_TYPE_STRING:
        newCell.setCellValue(oldCell.getRichStringCellValue());
        break;
    case HSSFCell.CELL_TYPE_NUMERIC:
        newCell.setCellValue(oldCell.getNumericCellValue());
        break;
    case HSSFCell.CELL_TYPE_BLANK:
        newCell.setCellType(HSSFCell.CELL_TYPE_BLANK);
        break;
    case HSSFCell.CELL_TYPE_BOOLEAN:
        newCell.setCellValue(oldCell.getBooleanCellValue());
        break;
    case HSSFCell.CELL_TYPE_ERROR:
        newCell.setCellErrorValue(oldCell.getErrorCellValue());
        break;
    case HSSFCell.CELL_TYPE_FORMULA:
        newCell.setCellFormula(oldCell.getCellFormula());
        break;
    default:
        break;
    }
}

From source file:com.wangzhu.poi.ExcelToHtmlConverter.java

License:Apache License

protected boolean processCell(HSSFCell cell, Element tableCellElement, int normalWidthPx, int maxSpannedWidthPx,
        float normalHeightPt) {
    final HSSFCellStyle cellStyle = cell.getCellStyle();

    String value;/*from  w ww  . j a  va2  s. c om*/
    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
        // XXX: enrich
        value = cell.getRichStringCellValue().getString();
        break;
    case Cell.CELL_TYPE_FORMULA:
        switch (cell.getCachedFormulaResultType()) {
        case Cell.CELL_TYPE_STRING:
            HSSFRichTextString str = cell.getRichStringCellValue();
            if ((str != null) && (str.length() > 0)) {
                value = (str.toString());
            } else {
                value = ExcelToHtmlUtils.EMPTY;
            }
            break;
        case Cell.CELL_TYPE_NUMERIC:
            HSSFCellStyle style = cellStyle;
            if (style == null) {
                value = String.valueOf(cell.getNumericCellValue());
            } else {
                value = (this._formatter.formatRawCellContents(cell.getNumericCellValue(),
                        style.getDataFormat(), style.getDataFormatString()));
            }
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            value = String.valueOf(cell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_ERROR:
            value = ErrorEval.getText(cell.getErrorCellValue());
            break;
        default:
            ExcelToHtmlConverter.logger.log(POILogger.WARN,
                    "Unexpected cell cachedFormulaResultType (" + cell.getCachedFormulaResultType() + ")");
            value = ExcelToHtmlUtils.EMPTY;
            break;
        }
        break;
    case Cell.CELL_TYPE_BLANK:
        value = ExcelToHtmlUtils.EMPTY;
        break;
    case Cell.CELL_TYPE_NUMERIC:
        value = this._formatter.formatCellValue(cell);
        break;
    case Cell.CELL_TYPE_BOOLEAN:
        value = String.valueOf(cell.getBooleanCellValue());
        break;
    case Cell.CELL_TYPE_ERROR:
        value = ErrorEval.getText(cell.getErrorCellValue());
        break;
    default:
        ExcelToHtmlConverter.logger.log(POILogger.WARN, "Unexpected cell type (" + cell.getCellType() + ")");
        return true;
    }

    final boolean noText = ExcelToHtmlUtils.isEmpty(value);
    final boolean wrapInDivs = !noText && this.isUseDivsToSpan() && !cellStyle.getWrapText();

    final short cellStyleIndex = cellStyle.getIndex();
    if (cellStyleIndex != 0) {
        HSSFWorkbook workbook = cell.getRow().getSheet().getWorkbook();
        String mainCssClass = this.getStyleClassName(workbook, cellStyle);
        if (wrapInDivs) {
            tableCellElement.setAttribute("class", mainCssClass + " " + this.cssClassContainerCell);
        } else {
            tableCellElement.setAttribute("class", mainCssClass);
        }

        if (noText) {
            /*
             * if cell style is defined (like borders, etc.) but cell text
             * is empty, add "&nbsp;" to output, so browser won't collapse
             * and ignore cell
             */
            value = "\u00A0";
        }
    }

    if (this.isOutputLeadingSpacesAsNonBreaking() && value.startsWith(" ")) {
        StringBuffer builder = new StringBuffer();
        for (int c = 0; c < value.length(); c++) {
            if (value.charAt(c) != ' ') {
                break;
            }
            builder.append('\u00a0');
        }

        if (value.length() != builder.length()) {
            builder.append(value.substring(builder.length()));
        }

        value = builder.toString();
    }

    Text text = this.htmlDocumentFacade.createText(value);

    if (wrapInDivs) {
        Element outerDiv = this.htmlDocumentFacade.createBlock();
        outerDiv.setAttribute("class", this.cssClassContainerDiv);

        Element innerDiv = this.htmlDocumentFacade.createBlock();
        StringBuffer innerDivStyle = new StringBuffer();
        innerDivStyle.append("position:absolute;min-width:");
        innerDivStyle.append(normalWidthPx);
        innerDivStyle.append("px;");
        if (maxSpannedWidthPx != Integer.MAX_VALUE) {
            innerDivStyle.append("max-width:");
            innerDivStyle.append(maxSpannedWidthPx);
            innerDivStyle.append("px;");
        }
        innerDivStyle.append("overflow:hidden;max-height:");
        innerDivStyle.append(normalHeightPt);
        innerDivStyle.append("pt;white-space:nowrap;");
        ExcelToHtmlUtils.appendAlign(innerDivStyle, cellStyle.getAlignment());
        this.htmlDocumentFacade.addStyleClass(outerDiv, this.cssClassPrefixDiv, innerDivStyle.toString());

        innerDiv.appendChild(text);
        outerDiv.appendChild(innerDiv);
        tableCellElement.appendChild(outerDiv);
    } else {
        tableCellElement.appendChild(text);
    }

    return ExcelToHtmlUtils.isEmpty(value) && (cellStyleIndex == 0);
}

From source file:com.xpn.xwiki.plugin.lucene.textextraction.MSExcelTextExtractor.java

License:Open Source License

/**
 * Extracts all text from each cell of the sheet
 *//*  w w w.  j  ava2s. c o m*/
private void parseCell(HSSFCell cell, StringBuffer cleanBuffer) {
    String cellValue = null;

    if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
        cellValue = cell.getRichStringCellValue().getString();
    } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
        HSSFCellStyle style = cell.getCellStyle();
        short formatId = style.getDataFormat();
        String formatPattern = mDataFormat.getFormat(formatId);
        formatPattern = replace(formatPattern, "\\ ", " ");

        if (isCellDateFormatted(cell)) {
            // This is a date
            formatPattern = replace(formatPattern, "mmmm", "MMMM");
            formatPattern = replace(formatPattern, "/", ".");
            SimpleDateFormat format;
            try {
                format = new SimpleDateFormat(formatPattern);
            } catch (Throwable thr) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Creating date format failed: '" + formatPattern + "'", thr);
                }
                format = new SimpleDateFormat();
            }

            double numberValue = cell.getNumericCellValue();
            Date date = HSSFDateUtil.getJavaDate(numberValue);
            cellValue = format.format(date);
        } else {
            // This is a Number
            DecimalFormat format;
            try {
                format = new DecimalFormat(formatPattern);
            } catch (Throwable thr) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Creating number format failed: '" + formatPattern + "'", thr);
                }
                format = new DecimalFormat();
            }

            double numberValue = cell.getNumericCellValue();
            cellValue = format.format(numberValue);
        }
    }

    if (cellValue != null) {
        cellValue = cellValue.trim();
        if (cellValue.length() != 0) {
            cleanBuffer.append(cellValue);
            cleanBuffer.append(" ");
        }
    }
}

From source file:de.alpharogroup.export.excel.poi.ExportExcelExtensions.java

License:Open Source License

/**
 * Exportiert die bergebene excel-Datei in eine Liste mit zweidimensionalen Arrays fr jeweils
 * ein sheet in der excel-Datei./* ww w . j  a  v a2s.com*/
 *
 * @param excelSheet
 *            Die excel-Datei.
 * @return Gibt eine Liste mit zweidimensionalen Arrays fr jeweils ein sheet in der excel-Datei
 *         zurck.
 * @throws IOException
 *             Fals ein Fehler beim Lesen aufgetreten ist.
 * @throws FileNotFoundException
 *             Fals die excel-Datei nicht gefunden wurde.
 */
public static List<String[][]> exportWorkbook(final File excelSheet) throws IOException, FileNotFoundException {
    final POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(excelSheet));
    final HSSFWorkbook wb = new HSSFWorkbook(fs);

    final int numberOfSheets = wb.getNumberOfSheets();
    final List<String[][]> sheetList = new ArrayList<>();
    for (int sheetNumber = 0; sheetNumber < numberOfSheets; sheetNumber++) {
        HSSFSheet sheet = null;
        sheet = wb.getSheetAt(sheetNumber);
        final int rows = sheet.getLastRowNum();

        final int columns = sheet.getRow(0).getLastCellNum();
        String[][] excelSheetInTDArray = null;
        excelSheetInTDArray = new String[rows + 1][columns];
        for (int i = 0; i <= rows; i++) {
            final HSSFRow row = sheet.getRow(i);
            if (null != row) {
                for (int j = 0; j < columns; j++) {
                    final HSSFCell cell = row.getCell(j);
                    if (null == cell) {
                        excelSheetInTDArray[i][j] = "";
                    } else {
                        final int cellType = cell.getCellType();
                        if (cellType == Cell.CELL_TYPE_BLANK) {
                            excelSheetInTDArray[i][j] = "";
                        } else if (cellType == Cell.CELL_TYPE_BOOLEAN) {
                            excelSheetInTDArray[i][j] = Boolean.toString(cell.getBooleanCellValue());
                        } else if (cellType == Cell.CELL_TYPE_ERROR) {
                            excelSheetInTDArray[i][j] = "";
                        } else if (cellType == Cell.CELL_TYPE_FORMULA) {
                            excelSheetInTDArray[i][j] = cell.getCellFormula();
                        } else if (cellType == Cell.CELL_TYPE_NUMERIC) {
                            excelSheetInTDArray[i][j] = Double.toString(cell.getNumericCellValue());
                        } else if (cellType == Cell.CELL_TYPE_STRING) {
                            excelSheetInTDArray[i][j] = cell.getRichStringCellValue().getString();
                        }
                    }
                }
            }
        }
        sheetList.add(excelSheetInTDArray);
    }
    wb.close();
    return sheetList;
}

From source file:de.alpharogroup.export.excel.poi.ExportExcelExtensions.java

License:Open Source License

/**
 * Exportiert die bergebene excel-Datei in eine geschachtelte Liste mit Listen von sheets und
 * Listen von den Zeilen der sheets von der excel-Datei.
 *
 * @param excelSheet/*from w ww.j  av  a 2s  .  co m*/
 *            Die excel-Datei.
 * @return Gibt eine Liste mit Listen von den sheets in der excel-Datei zurck. Die Listen mit
 *         den sheets beinhalten weitere Listen mit String die jeweils eine Zeile
 *         reprsentieren.
 * @throws IOException
 *             Fals ein Fehler beim Lesen aufgetreten ist.
 * @throws FileNotFoundException
 *             Fals die excel-Datei nicht gefunden wurde.
 */
public static List<List<List<String>>> exportWorkbookAsStringList(final File excelSheet)
        throws IOException, FileNotFoundException {
    final POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(excelSheet));
    final HSSFWorkbook wb = new HSSFWorkbook(fs);
    final int numberOfSheets = wb.getNumberOfSheets();
    final List<List<List<String>>> sl = new ArrayList<>();
    for (int sheetNumber = 0; sheetNumber < numberOfSheets; sheetNumber++) {
        HSSFSheet sheet = null;
        sheet = wb.getSheetAt(sheetNumber);
        final int rows = sheet.getLastRowNum();
        final int columns = sheet.getRow(0).getLastCellNum();
        final List<List<String>> excelSheetList = new ArrayList<>();
        for (int i = 0; i <= rows; i++) {
            final HSSFRow row = sheet.getRow(i);
            if (null != row) {
                final List<String> reihe = new ArrayList<>();
                for (int j = 0; j < columns; j++) {
                    final HSSFCell cell = row.getCell(j);
                    if (null == cell) {
                        reihe.add("");
                    } else {
                        final int cellType = cell.getCellType();
                        if (cellType == Cell.CELL_TYPE_BLANK) {
                            reihe.add("");
                        } else if (cellType == Cell.CELL_TYPE_BOOLEAN) {
                            reihe.add(Boolean.toString(cell.getBooleanCellValue()));
                        } else if (cellType == Cell.CELL_TYPE_ERROR) {
                            reihe.add("");
                        } else if (cellType == Cell.CELL_TYPE_FORMULA) {
                            reihe.add(cell.getCellFormula());
                        } else if (cellType == Cell.CELL_TYPE_NUMERIC) {
                            reihe.add(Double.toString(cell.getNumericCellValue()));
                        } else if (cellType == Cell.CELL_TYPE_STRING) {
                            reihe.add(cell.getRichStringCellValue().getString());
                        }
                    }
                }
                excelSheetList.add(reihe);
            }
        }
        sl.add(excelSheetList);
    }
    wb.close();
    return sl;
}

From source file:de.bezier.data.XlsReader.java

License:Creative Commons License

/**
*   Return an float value from a specific cell of the current sheet.
*
*   @param   rowNum   Row (vertically) to read from. First row is 0.
*   @param   cellNum Cell (horizontal) in the row to read from. Starts at 0.
*   @return   float The float value of that cell.
*//*w  w  w . ja va  2s.c  om*/

public float getFloat(int rowNum, int cellNum) {
    HSSFCell cell = getCell(rowNum, cellNum);

    if (cell == null)
        papplet.println("ERR, getFloat(): cell is null");

    if (!isCellType(cell, HSSFCell.CELL_TYPE_NUMERIC))
        papplet.println("ERR, getFloat(): wrong celltype");

    float i;
    try {
        i = (float) (cell.getNumericCellValue());
        return i;
    } catch (NumberFormatException nfe) {
        if (showWarnings)
            papplet.println(
                    "ERR, getFloat(" + rowNum + "," + cellNum + "): you are reading a text cell as float.");
    }
    i = Float.parseFloat(cell.getRichStringCellValue().toString().trim());
    return i;
}

From source file:edu.duke.cabig.c3pr.web.study.tabs.StudyEligibilityChecklistTab.java

License:BSD License

public void parseCadsrFile(Study study, POIFSFileSystem pfs, String name) {

    List<InclusionEligibilityCriteria> incList = null;
    List<ExclusionEligibilityCriteria> excList = null;
    if (study.getEpochByName(name) != null) {
        incList = study.getEpochByName(name).getInclusionEligibilityCriteria();
        excList = study.getEpochByName(name).getExclusionEligibilityCriteria();
    } else {/*from  ww  w  .  j  a  v a2s.  c  o  m*/
        return;
    }
    try {
        HSSFWorkbook wb = new HSSFWorkbook(pfs);
        HSSFSheet sheet = wb.getSheetAt(0);

        HSSFRow currentRow;
        HSSFCell currentCell;
        InclusionEligibilityCriteria inc = null;
        ExclusionEligibilityCriteria exc = null;

        Iterator rowIter = sheet.rowIterator();
        // iterating over the entire file
        while (rowIter.hasNext()) {
            currentRow = (HSSFRow) rowIter.next();

            // inclusion section
            if (currentRow.getCell((short) 0) != null
                    && currentRow.getCell((short) 0).getCellType() == HSSFCell.CELL_TYPE_STRING && currentRow
                            .getCell((short) 0).getRichStringCellValue().toString().startsWith(INCLUSION)) {
                // iterating over the inclusion rows
                HSSFRow innerCurrentRow;
                while (rowIter.hasNext()) {
                    innerCurrentRow = (HSSFRow) rowIter.next();
                    if (innerCurrentRow.getCell((short) 0) != null
                            && innerCurrentRow.getCell((short) 0).getCellType() == HSSFCell.CELL_TYPE_STRING
                            && innerCurrentRow.getCell((short) 0).getRichStringCellValue().toString()
                                    .startsWith(EXCLUSION)) {
                        currentRow = innerCurrentRow;
                        break;
                    }
                    currentCell = innerCurrentRow.getCell((short) 3);
                    if (currentCell != null && currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING
                            && currentCell.getRichStringCellValue().toString().length() > 0) {
                        // create the new inc and populate the list
                        if (inc != null) {
                            incList.add(inc);
                        }
                        inc = new InclusionEligibilityCriteria();
                        inc.setQuestionText(currentCell.getRichStringCellValue().toString());
                    } else {
                        // get the answers
                        currentCell = innerCurrentRow.getCell((short) 15);
                        if (currentCell != null && currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING
                                && currentCell.getRichStringCellValue().toString()
                                        .equalsIgnoreCase(NOT_APPLICABLE)) {
                            if (inc != null) {
                                inc.setNotApplicableIndicator(true);
                            }
                        }
                    }
                }
                // adding the last criteria to the list
                incList.add(inc);
            } // end of inclusion if

            // exclusion section
            if (currentRow.getCell((short) 0) != null
                    && currentRow.getCell((short) 0).getCellType() == HSSFCell.CELL_TYPE_STRING && currentRow
                            .getCell((short) 0).getRichStringCellValue().toString().startsWith(EXCLUSION)) {
                // iterating over the exclusion rows
                HSSFRow innerCurrentRow;
                while (rowIter.hasNext()) {
                    innerCurrentRow = (HSSFRow) rowIter.next();
                    // This if loop is not needed as we only have 1 inc section and 1 exc
                    // section
                    // however leaving it in place as it is harmless and will be useful if we
                    // ever have repeated inc/exc sections in the input file
                    if (innerCurrentRow.getCell((short) 0) != null
                            && innerCurrentRow.getCell((short) 0).getCellType() == HSSFCell.CELL_TYPE_STRING
                            && innerCurrentRow.getCell((short) 0).getRichStringCellValue().toString()
                                    .startsWith(INCLUSION)) {
                        currentRow = innerCurrentRow;
                        break;
                    }
                    currentCell = innerCurrentRow.getCell((short) 3);
                    if (currentCell != null && currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING
                            && currentCell.getRichStringCellValue().toString().length() > 0) {
                        // create the new exc and populate the list
                        if (exc != null) {
                            excList.add(exc);
                        }
                        exc = new ExclusionEligibilityCriteria();
                        exc.setQuestionText(currentCell.getRichStringCellValue().toString());
                    } else {
                        // get the answers
                        currentCell = innerCurrentRow.getCell((short) 15);
                        if (currentCell != null && currentCell.getRichStringCellValue() != null
                                && currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING && currentCell
                                        .getRichStringCellValue().toString().equalsIgnoreCase(NOT_APPLICABLE)) {
                            if (exc != null) {
                                exc.setNotApplicableIndicator(true);
                            }
                        }
                    }
                }
                // adding the last criteria to the list
                excList.add(exc);
            } // end of exclusion if
        } // end if while loop that iterates over the entire file.
    } catch (IOException ioe) {
        log.error(ioe.getMessage());
    }

}

From source file:edu.fcps.hutchison.LabelBuilder.java

License:Open Source License

protected String getCellValStr(HSSFCell cell) {
    if (cell == null) {
        return "";
    } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
        return Boolean.toString(cell.getBooleanCellValue());
    } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
        return Double.toString(cell.getNumericCellValue());
    } else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
        return cell.getRichStringCellValue().toString();
    } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
        return "";
    } else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
        return cell.getCellFormula();
    } else if (cell.getCellType() == HSSFCell.CELL_TYPE_ERROR) {
        return String.valueOf(cell.getErrorCellValue());
    } else {//from   w  w w  . j  av  a2 s. c om
        return "";
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.ConfigureXLS.java

License:Open Source License

@Override
protected void nonInteractiveConfig() {
    try {/*from   ww  w .  ja v  a  2 s. c om*/
        InputStream input = new FileInputStream(externalFile);
        POIFSFileSystem fs = new POIFSFileSystem(input);
        HSSFWorkbook workBook = new HSSFWorkbook(fs);
        HSSFSheet sheet = workBook.getSheetAt(0);

        // Calculate the number of rows and columns
        colInfo = new Vector<ImportColumnInfo>(16);

        Hashtable<Integer, Boolean> colTracker = new Hashtable<Integer, Boolean>();

        boolean firstRow = true;
        int col = 0;
        colTracker.clear();

        Vector<Integer> badHeads = new Vector<Integer>();
        Vector<Integer> emptyCols = new Vector<Integer>();
        checkHeadsAndCols(sheet, badHeads, emptyCols);

        if (firstRowHasHeaders && badHeads.size() > 0) {
            status = ConfigureExternalDataIFace.Status.Error;
            showBadHeadingsMsg(badHeads, null, getResourceString("Error"));
            return;
        }

        // Iterate over each row in the sheet
        @SuppressWarnings("unchecked")
        Iterator<HSSFRow> rows = sheet.rowIterator();
        while (rows.hasNext()) {
            HSSFRow row = rows.next();
            if (firstRow || numRows == 1) {
                // Iterate over each cell in the row and print out the cell's content
                int colNum = 0;
                int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum());
                while (colNum < maxSize) {
                    if (emptyCols.indexOf(new Integer(colNum)) == -1) {
                        ImportColumnInfo.ColumnType disciplinee = ImportColumnInfo.ColumnType.Integer;
                        String value = null;
                        boolean skip = false;
                        HSSFCell cell = row.getCell(colNum);
                        if (cell == null) {
                            //assuming numRows == 1 or not firstRowHasHeaders.
                            //the call to checkHeadsAndCols would have already blank headers.
                            value = "";
                            disciplinee = ImportColumnInfo.ColumnType.String;
                        } else
                            switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                double numeric = cell.getNumericCellValue();
                                value = Double.toString(numeric);
                                disciplinee = ImportColumnInfo.ColumnType.Double;
                                break;
                            case HSSFCell.CELL_TYPE_STRING:
                                HSSFRichTextString richVal = cell.getRichStringCellValue();
                                value = richVal.getString().trim();
                                disciplinee = ImportColumnInfo.ColumnType.String;
                                break;
                            case HSSFCell.CELL_TYPE_BLANK:
                                value = "";
                                disciplinee = ImportColumnInfo.ColumnType.String;
                                break;
                            case HSSFCell.CELL_TYPE_BOOLEAN:
                                boolean bool = cell.getBooleanCellValue();
                                value = Boolean.toString(bool);
                                disciplinee = ImportColumnInfo.ColumnType.Boolean;
                                break;
                            default:
                                skip = true;
                                break;
                            }

                        if (numRows == 1 && !skip) {
                            colInfo.get(col).setData(value);
                            col++;
                        } else if (!skip) {
                            if (firstRowHasHeaders) {
                                colInfo.add(new ImportColumnInfo(colNum, disciplinee, value, value, null, null,
                                        null));
                                colTracker.put(col, true);
                            } else {
                                String colName = getResourceString("DEFAULT_COLUMN_NAME") + " " + (colNum + 1);
                                colInfo.add(new ImportColumnInfo(colNum, disciplinee, colName, colName, null,
                                        null, null));
                                colTracker.put(colNum, true);
                            }
                            numCols++;
                        }
                    }
                    colNum++;
                }
                firstRow = false;
            }
            numRows++;
        }
        Collections.sort(colInfo);
        readMappings(fs);
        status = Status.Valid;
    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ConfigureXLS.class, ex);
        status = Status.Error;
    }
}