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

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

Introduction

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

Prototype

double getNumericCellValue();

Source Link

Document

Get the value of the cell as a number.

Usage

From source file:com.vaadin.addon.spreadsheet.ConditionalFormatter.java

/**
 * Checks if the given cell value matches a
 * {@link ConditionalFormattingRule} of <code>VALUE_IS</code> type. Covers
 * all cell types and comparison operations.
 *
 * @param cell/*from w  w  w  .  j av  a2s . c o  m*/
 *            Target cell
 * @param rule
 *            Conditional formatting rule to match against.
 * @return True if the given cells value matches the given
 *         <code>VALUE_IS</code> rule, false otherwise
 */
protected boolean matchesValue(Cell cell, ConditionalFormattingRule rule) {

    boolean isFormulaType = cell.getCellType() == Cell.CELL_TYPE_FORMULA;
    boolean isFormulaStringType = isFormulaType && cell.getCachedFormulaResultType() == Cell.CELL_TYPE_STRING;
    boolean isFormulaBooleanType = isFormulaType && cell.getCachedFormulaResultType() == Cell.CELL_TYPE_BOOLEAN;
    boolean isFormulaNumericType = isFormulaType && cell.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC;

    if (isFormulaType) {
        try {
            // make sure we have the latest value for formula cells
            getFormulaEvaluator().evaluateFormulaCell(cell);
        } catch (NotImplementedException e) {
            LOGGER.log(Level.FINEST, e.getMessage(), e);
            return false;
        }
    }

    // other than numerical types
    if (cell.getCellType() == Cell.CELL_TYPE_STRING || isFormulaStringType) {

        // Excel stores conditional formatting strings surrounded with ", so
        // we must surround the cell value. String cell value from POI is
        // never null.
        String quotedStringValue = String.format("\"%s\"", cell.getStringCellValue());

        // Excel string comparison ignores case
        switch (rule.getComparisonOperation()) {
        case ComparisonOperator.EQUAL:
            return quotedStringValue.equalsIgnoreCase(rule.getFormula1());
        case ComparisonOperator.NOT_EQUAL:
            return !quotedStringValue.equalsIgnoreCase(rule.getFormula1());
        }
    }
    if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN || isFormulaBooleanType) {
        // not sure if this is used, since no boolean option exists in
        // Excel..

        Boolean formulaVal = Boolean.parseBoolean(rule.getFormula1());

        switch (rule.getComparisonOperation()) {
        case ComparisonOperator.EQUAL:
            return cell.getBooleanCellValue() == formulaVal;
        case ComparisonOperator.NOT_EQUAL:
            return cell.getBooleanCellValue() != formulaVal;
        }
    }

    // numerical types
    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC || isFormulaNumericType) {

        double formula1Val = -1;
        try {
            formula1Val = Double.valueOf(rule.getFormula1());

        } catch (NumberFormatException w) {
            // non-numeric formatting rules cannot match
            return false;
        }

        switch (rule.getComparisonOperation()) {

        case ComparisonOperator.EQUAL:
            return cell.getNumericCellValue() == formula1Val;
        case ComparisonOperator.NOT_EQUAL:
            return cell.getNumericCellValue() != formula1Val;

        case ComparisonOperator.LT:
            return cell.getNumericCellValue() < formula1Val;
        case ComparisonOperator.LE:
            return cell.getNumericCellValue() <= formula1Val;
        case ComparisonOperator.GT:
            return cell.getNumericCellValue() > formula1Val;
        case ComparisonOperator.GE:
            return cell.getNumericCellValue() >= formula1Val;

        case ComparisonOperator.BETWEEN:
            boolean lt = cell.getNumericCellValue() >= formula1Val;
            boolean gt = cell.getNumericCellValue() <= Double.valueOf(rule.getFormula2());
            return lt && gt;

        case ComparisonOperator.NOT_BETWEEN:
            lt = cell.getNumericCellValue() <= formula1Val;
            gt = cell.getNumericCellValue() >= Double.valueOf(rule.getFormula2());
            return lt && gt;
        }
    }

    return false;
}

From source file:com.validation.manager.core.tool.requirement.importer.RequirementImporter.java

License:Apache License

@Override
public List<Requirement> importFile(boolean header) throws RequirementImportException, VMException {
    queue.clear();//from   w  ww.j  a v a 2s  . com
    List<Integer> errors = new ArrayList<>();
    HashMap<String, Object> parameters = new HashMap<>();
    List<Object> result;
    if (toImport == null) {
        throw new RequirementImportException("message.requirement.import.file.null");
    } else if (!toImport.exists()) {
        throw new RequirementImportException("message.requirement.import.file.invalid");
    } else {
        //Excel support
        if (toImport.getName().endsWith(".xls") || toImport.getName().endsWith(".xlsx")) {
            try {
                Workbook wb = loadFile();
                org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);
                int rows = sheet.getPhysicalNumberOfRows();
                int r = 0;
                if (header) {
                    //Skip header row
                    r++;
                }
                for (; r < rows; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    if (row.getCell(0) == null) {
                        LOG.log(Level.WARNING, "Found an empty row on line: {0}. " + "Stopping processing", r);
                        break;
                    }
                    int cells = row.getPhysicalNumberOfCells();
                    if (cells < 2) {
                        LOG.log(Level.INFO, "Processing row: {0}", r);
                        LOG.warning(ResourceBundle
                                .getBundle("com.validation.manager.resources.VMMessages", Locale.getDefault())
                                .getString("message.requirement.import.missing.column")
                                .replaceAll("%c", "" + cells));
                        errors.add(r);
                    } else {
                        Requirement requirement = new Requirement();
                        LOG.log(Level.FINE, "Row: {0}", r);
                        for (int c = 0; c < cells; c++) {
                            Cell cell = row.getCell(c);
                            String value = "";
                            if (cell != null) {
                                switch (cell.getCellTypeEnum()) {
                                case FORMULA:
                                    value = cell.getCellFormula();
                                    break;
                                case NUMERIC:
                                    value = "" + cell.getNumericCellValue();
                                    break;
                                case STRING:
                                    value = cell.getStringCellValue();
                                    break;
                                default:
                                    value = "";
                                    break;
                                }
                            }
                            //Remove any extra spaces.
                            value = value.trim();
                            switch (c) {
                            case 0:
                                //Unique ID
                                LOG.fine("Setting id");
                                requirement.setUniqueId(value);
                                break;
                            case 1:
                                //Description
                                LOG.fine("Setting desc");
                                requirement.setDescription(value);
                                break;
                            case 2:
                                //Optional Requirement type
                                LOG.fine("Setting requirement type");
                                parameters.clear();
                                parameters.put("name", value);
                                result = namedQuery("RequirementType.findByName", parameters);
                                if (result.isEmpty()) {
                                    //Assume a default
                                    parameters.clear();
                                    parameters.put("name", "SW");
                                    result = namedQuery("RequirementType.findByName", parameters);
                                }
                                requirement.setRequirementTypeId((RequirementType) result.get(0));
                                break;
                            case 3:
                                //Optional notes
                                LOG.fine("Setting notes");
                                requirement.setNotes(value);
                                break;
                            default:
                                throw new RequirementImportException("Invalid column detected: " + c);
                            }
                            LOG.fine(value);
                        }
                        //This shouldn't be null
                        assert rsn != null : "Requirement Spec Node is null?";
                        requirement.setRequirementSpecNode(rsn);
                        parameters.clear();
                        parameters.put("status", "general.open");
                        result = namedQuery("RequirementStatus.findByStatus", parameters);
                        requirement.setRequirementStatusId((RequirementStatus) result.get(0));
                        assert requirement.getUniqueId() != null
                                && !requirement.getUniqueId().isEmpty() : "Invalid requirement detected!";
                        try {
                            if (!exists(requirement) && !queue.containsKey(requirement.getUniqueId())) {
                                queue.put(requirement.getUniqueId(), requirement);
                            }
                        } catch (IllegalOrphanException | NonexistentEntityException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                }
            } catch (InvalidFormatException | IOException ex) {
                LOG.log(Level.SEVERE, null, ex);
            } finally {
                try {
                    if (inp != null) {
                        inp.close();
                    }
                } catch (IOException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
            }
        } else if (toImport.getName().endsWith(".xml")) {
            throw new RequirementImportException("XML importing not supported yet.");
        } else if (toImport.getName().endsWith(".doc") || toImport.getName().endsWith(".docx")) {
            try {
                TableExtractor te = new TableExtractor(toImport);
                List<DefaultTableModel> tables = te.extractTables();
                Requirement requirement = new Requirement();
                LOG.log(Level.INFO, "Imported {0} tables!", tables.size());
                int count = 1;
                for (DefaultTableModel model : tables) {
                    int rows = model.getRowCount();
                    int cols = model.getColumnCount();
                    LOG.log(Level.INFO, "Processing table {0} with {1} " + "rows and {2} columns.",
                            new Object[] { count, rows, cols });
                    for (int r = 0; r < rows; r++) {
                        for (int c = 0; c < cols; c++) {
                            String value = (String) model.getValueAt(rows, cols);
                            switch (c) {
                            case 0:
                                //Unique ID
                                LOG.fine("Setting id");
                                requirement.setUniqueId(value);
                                break;
                            case 1:
                                //Description
                                LOG.fine("Setting desc");
                                requirement.setDescription(value);
                                break;
                            case 2:
                                //Requirement type
                                LOG.fine("Setting requirement type");
                                parameters.clear();
                                parameters.put("name", value);
                                result = namedQuery("RequirementType.findByName", parameters);
                                if (result.isEmpty()) {
                                    //Assume a default
                                    parameters.clear();
                                    parameters.put("name", "SW");
                                    result = namedQuery("RequirementType.findByName", parameters);
                                }
                                requirement.setRequirementTypeId((RequirementType) result.get(0));
                                break;
                            case 3:
                                //Optional notes
                                LOG.fine("Setting notes");
                                requirement.setNotes(value);
                                break;
                            default:
                                throw new RuntimeException("Invalid column detected: " + c);
                            }
                        }
                    }
                }
            } catch (IOException | ClassNotFoundException ex) {
                Exceptions.printStackTrace(ex);
            }
        } else {
            throw new RequirementImportException("Unsupported file format: " + toImport.getName());
        }
        StringBuilder sb = new StringBuilder("Rows with erros:\n");
        errors.stream().forEach((line) -> {
            sb.append(line).append('\n');
        });
        if (!errors.isEmpty()) {
            getDefault().lookup(MessageHandler.class).info(sb.toString());
        }
        return new ArrayList(queue.values());
    }
}

From source file:com.validation.manager.core.tool.step.importer.StepImporter.java

License:Apache License

@Override
public List<Step> importFile(boolean header) throws TestCaseImportException {
    steps.clear();//from ww w . j  a v  a 2 s. c  o m
    if (toImport == null) {
        throw new TestCaseImportException("message.step.import.file.null");
    } else if (!toImport.exists()) {
        throw new TestCaseImportException("message.step.import.file.invalid");
    } else {
        //Excel support
        if (toImport.getName().endsWith(".xls") || toImport.getName().endsWith(".xlsx")) {
            InputStream inp = null;
            try {
                inp = new FileInputStream(toImport);
                org.apache.poi.ss.usermodel.Workbook wb = create(inp);
                org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);
                int rows = sheet.getPhysicalNumberOfRows();
                int r = 0;
                if (header) {
                    //Skip header row
                    r++;
                }
                for (; r < rows; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    int cells = row.getPhysicalNumberOfCells();
                    if (row.getCell(0) == null) {
                        LOG.log(Level.WARNING, "Found an empty row on line: {0}. " + "Stopping processing", r);
                        break;
                    }
                    if (cells < 2) {
                        throw new TestCaseImportException(RB.getString("message.step.import.missing.column")
                                .replaceAll("%c", "" + cells));
                    }
                    Step step = new Step();
                    step.setRequirementList(new ArrayList<>());
                    HashMap<String, Object> parameters = new HashMap<>();
                    List<Object> result;
                    LOG.log(Level.FINE, "Row: {0}", r);
                    for (int c = 0; c < cells; c++) {
                        Cell cell = row.getCell(c);
                        String value = null;
                        if (cell != null) {
                            switch (cell.getCellType()) {

                            case Cell.CELL_TYPE_FORMULA:
                                value = cell.getCellFormula();
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                value = "" + cell.getNumericCellValue();
                                break;
                            case Cell.CELL_TYPE_STRING:
                                value = cell.getStringCellValue();
                                break;
                            default:
                                //Do nothing.
                            }
                        }
                        switch (c) {
                        case 0:
                            if (value != null) {
                                //Sequence
                                LOG.fine("Setting sequence");
                                Integer val = value.contains(".")
                                        ? valueOf(value.substring(0, value.indexOf(".")))
                                        : valueOf(value);
                                if (!tc.getStepList().isEmpty()) {
                                    int max = 0;
                                    for (Step s : tc.getStepList()) {
                                        if (s.getStepSequence() > max) {
                                            max = s.getStepSequence();
                                        }
                                    }
                                    //Make sure there isn't one on that sequence already
                                    val += max;
                                }
                                step.setStepSequence(val);
                            }
                            break;
                        case 1:
                            if (value != null) {
                                //Text
                                LOG.fine("Setting text");
                                step.setText(value.getBytes("UTF-8"));
                            }
                            break;
                        case 2:
                            //Optional Related requirements
                            if (value != null && !value.trim().isEmpty()) {
                                LOG.fine("Setting related requirements");
                                StringTokenizer st = new StringTokenizer(value, ",");
                                while (st.hasMoreTokens()) {
                                    String token = st.nextToken().trim();
                                    parameters.clear();
                                    parameters.put("uniqueId", token);
                                    result = namedQuery("Requirement.findByUniqueId", parameters);
                                    if (!result.isEmpty()) {
                                        for (Object o : result) {
                                            step.getRequirementList().add((Requirement) o);
                                        }
                                    }
                                }
                            }
                            break;
                        case 3:
                            if (value != null) {
                                //Optional Expected result
                                LOG.fine("Setting expected result");
                                step.setExpectedResult(value.getBytes("UTF-8"));
                            }
                            break;
                        case 4:
                            if (value != null) {
                                //Optional notes
                                LOG.fine("Setting notes");
                                step.setNotes(value);
                            }
                            break;

                        default:
                            throw new RuntimeException("Invalid column detected: " + c);
                        }
                        LOG.fine(value);
                    }
                    step.setTestCase(tc);
                    steps.add(step);
                }
            } catch (InvalidFormatException | IOException ex) {
                LOG.log(Level.SEVERE, null, ex);
            } finally {
                try {
                    if (inp != null) {
                        inp.close();
                    }
                } catch (IOException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
            }
        } else if (toImport.getName().endsWith(".xml")) {
            throw new TestCaseImportException("XML importing not supported yet.");
        } else {
            throw new TestCaseImportException("Unsupported file format: " + toImport.getName());
        }
        return steps;
    }
}

From source file:com.veeduria.web.cargaarchivo.aut.th.CargaPlanta.java

public void cargarArchivoEmpleados(Path rutaArchivo) {
    //Get first sheet from the workbook
    try {//from   ww w.  ja  v a 2s . c o  m
        StringBuilder strBSql = new StringBuilder();
        HSSFWorkbook workbook = new HSSFWorkbook(Files.newInputStream(rutaArchivo, StandardOpenOption.READ));
        HSSFSheet sheet = workbook.getSheet("EMPLEADOS");
        if (sheet != null) {
            Iterator<org.apache.poi.ss.usermodel.Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = (Row) rowIterator.next();
                if (row.getRowNum() >= 10) {
                    if (row.getCell(0) != null) {
                        for (int i = 0; i < 42; i++) {
                            Cell cell = row.getCell(i);
                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_BOOLEAN:
                                strBSql.append(cell.getBooleanCellValue());
                                strBSql.append(",");
                                //  System.out.print(cell.getBooleanCellValue() + "\t\t");
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                strBSql.append(cell.getNumericCellValue());
                                strBSql.append(",");
                                //   System.out.print(cell.getNumericCellValue() + "\t\t");
                                break;
                            case Cell.CELL_TYPE_STRING:
                                strBSql.append(",'");
                                strBSql.append(cell.getStringCellValue());
                                strBSql.append("',");
                                //  System.out.print(cell.getStringCellValue() + "\t\t");
                                break;

                            }

                        }
                        strBSql.replace(strBSql.length() - 1, strBSql.length(), "");
                    }

                }
                strBSql.append(System.getProperty("line.separator"));
            }

            System.out.println("");
        }

        //            FileOutputStream out = new FileOutputStream(new File(System.getProperty("user.home") + File.separator + "test.xls"));
        //            workbook.write(out);
        //            out.close();
    } catch (IOException e) {
        Logger.getLogger(VigilarCarpetaSLBean.class.getName()).log(Level.SEVERE, null, e);
    }
}

From source file:com.vermeg.convertisseur.service.ConvServiceImpl.java

/**
 *
 * @param file// w ww  . j a  v  a  2 s.  c om
 * @return
 * @throws FileNotFoundException
 * @throws InvalidFormatException
 * @throws IOException
 */
/*this method convert a multipart file to json object */
@Override
public JSONObject convert(MultipartFile file, String name)
        throws FileNotFoundException, InvalidFormatException, IOException {

    // File file = new File("C:\\Users\\Ramzi\\Documents\\PFE\\developpement\\avancement.xlsx");

    File filez = File.createTempFile("fichier", "xslx");
    file.transferTo(filez);
    FileInputStream inp = new FileInputStream(filez);
    Workbook workbook = WorkbookFactory.create(inp);
    //Sheet sheet = workbook.getSheetAt( 0 );
    Sheet sheet = workbook.getSheet(name);
    // Start constructing JSON.
    JSONObject json = new JSONObject();

    // Iterate through the rows.
    JSONArray rows = new JSONArray();
    for (Iterator<Row> rowsIT = sheet.rowIterator(); rowsIT.hasNext();) {
        Row row = rowsIT.next();
        JSONObject jRow = new JSONObject();

        // Iterate through the cells.
        JSONArray cells = new JSONArray();
        for (Iterator<Cell> cellsIT = row.cellIterator(); cellsIT.hasNext();) {
            Cell cell = cellsIT.next();
            // System.out.println(cell.getCellType());
            //           cells.put(cell.getDateCellValue());
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                cells.put(cell.getRichStringCellValue().getString());
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    cells.put(cell.getDateCellValue());
                } else {
                    cells.put(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cells.put(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                cells.put(cell.getCellFormula());
                break;
            default:
                System.out.println();
            }
        }
        jRow.put("cell", cells);
        rows.put(cells);
        //rows.put( jRow );
    }

    // Create the JSON.
    json.put("rows", rows);
    System.out.println(json.toString());
    return json;
}

From source file:com.vermeg.convertisseur.service.ConvServiceImpl.java

@Override
public JSONObject convert(String file, String name)
        throws FileNotFoundException, InvalidFormatException, IOException {

    // File file = new File("C:\\Users\\Ramzi\\Documents\\PFE\\developpement\\avancement.xlsx");

    File filez = File.createTempFile("fichier", "xslx");
    byte[] data = Base64.decodeBase64(file);
    FileOutputStream fos = new FileOutputStream(filez);
    fos.write(data);/*from w  ww  .j a  v  a2s .c o m*/
    fos.close();
    //file.transferTo(filez);
    FileInputStream inp = new FileInputStream(filez);
    Workbook workbook = WorkbookFactory.create(inp);
    //Sheet sheet = workbook.getSheetAt( 0 );
    Sheet sheet = workbook.getSheet(name);
    // Start constructing JSON.
    JSONObject json = new JSONObject();

    // Iterate through the rows.
    JSONArray rows = new JSONArray();
    for (Iterator<Row> rowsIT = sheet.rowIterator(); rowsIT.hasNext();) {
        Row row = rowsIT.next();
        JSONObject jRow = new JSONObject();

        // Iterate through the cells.
        JSONArray cells = new JSONArray();
        for (Iterator<Cell> cellsIT = row.cellIterator(); cellsIT.hasNext();) {
            Cell cell = cellsIT.next();

            if (cell.getCellType() == CELL_TYPE_NUMERIC) {
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    cells.put(cell.getDateCellValue());
                } else
                    cells.put(cell.getNumericCellValue());
            } else
                cells.put(cell.getStringCellValue());
        }
        jRow.put("cell", cells);
        rows.put(cells);
        //rows.put( jRow );
    }

    // Create the JSON.
    json.put("rows", rows);
    System.out.println(json.toString());
    return json;
}

From source file:com.vertec.daoimpl.AttendanceDAOImpl.java

public List<Object> readexcel(String path) {
    //        String data = "";
    List<Object> table = new ArrayList<Object>();
    try {//  w  w  w  .  java2 s  . c om
        // Get the workbook instance for XLSX file
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(path));

        // Get first sheet from the workbook
        XSSFSheet sheet = wb.getSheetAt(0);

        Row row;
        Cell cell;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {
            row = rowIterator.next();

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            List<String> rows = new ArrayList<String>();
            while (cellIterator.hasNext()) {
                cell = cellIterator.next();

                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    rows.add(cell.getRichStringCellValue().getString());
                    //                            data+=cell.getRichStringCellValue().getString();
                    //                            System.out.print(cell.getRichStringCellValue().getString());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {

                        rows.add(cell.getDateCellValue() + "");
                        //                                data+=cell.getDateCellValue();
                        //                                System.out.print(cell.getDateCellValue());
                    } else {
                        rows.add(cell.getNumericCellValue() + "");
                        //                                data+=cell.getNumericCellValue();
                        //                                System.out.print(cell.getNumericCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    rows.add(cell.getBooleanCellValue() + "");
                    //                            data+=cell.getBooleanCellValue();
                    //                            System.out.print(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    rows.add(cell.getCellFormula() + "");
                    //                            data+=cell.getCellFormula();
                    //                            System.out.print(cell.getCellFormula());
                    break;
                default:
                    //                            System.out.print("");
                }
                //                    data += "-";
                //                    System.out.print(" - ");
            }
            table.add(rows);
            //                data += ";;;";
            //                System.out.println(";;;");
        }
    } catch (Exception e) {
        System.err.println("Exception :" + e.getMessage());
    }
    return table;
}

From source file:com.vertec.daoimpl.AttendanceDAOImpl.java

public String readexcel2(String path) {
    try {/*  ww  w  .j av  a 2 s. c om*/
        // Get the workbook instance for XLSX file
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(path));

        // Get first sheet from the workbook
        XSSFSheet sheet = wb.getSheetAt(0);

        Row row;
        Cell cell;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {
            row = rowIterator.next();

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {
                cell = cellIterator.next();

                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    System.out.print(cell.getRichStringCellValue().getString());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        System.out.print(cell.getDateCellValue());
                    } else {
                        System.out.print(cell.getNumericCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.print(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    System.out.print(cell.getCellFormula());
                    break;
                default:
                    System.out.print("");
                }
                System.out.print(" - ");
            }
            System.out.println(";;;");
        }
    } catch (Exception e) {
        System.err.println("Exception :" + e.getMessage());
    }
    return null;
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * Adds the values from excel./*w w  w. j a  v a  2 s . co  m*/
 * 
 * @param path
 *            the path
 * @param index
 *            the index
 * @return the string[][]
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws InvalidFormatException
 *             the invalid format exception
 */
public final String[][] addValuesFromExcel(final String path, final String index)
        throws IOException, InvalidFormatException {

    String cellStringValue = null;
    double cellDoubleValue = 0;
    Boolean cellBooleanValue;
    byte cellErrorValue = 0;
    String[][] arrExcelContent;
    FileInputStream file = null;
    Workbook workbook = null;

    Sheet sheet = null;
    try {
        file = new FileInputStream(new File(path));
        workbook = WorkbookFactory.create(file);
        sheet = workbook.getSheetAt(Integer.parseInt(index));
        Iterator<Row> rowIterator = sheet.iterator();
        arrExcelContent = new String[sheet.getPhysicalNumberOfRows()][];
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            int rowNumber = row.getRowNum();
            Iterator<Cell> cellIterator = row.cellIterator();
            arrExcelContent[rowNumber] = new String[sheet.getRow(rowNumber).getPhysicalNumberOfCells()];
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                int cellNumber = cell.getColumnIndex();
                if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                    cellStringValue = cell.getStringCellValue();
                    arrExcelContent[rowNumber][cellNumber] = cellStringValue;
                } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
                    cellBooleanValue = cell.getBooleanCellValue();
                    arrExcelContent[rowNumber][cellNumber] = cellBooleanValue.toString();
                } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
                    cellErrorValue = cell.getErrorCellValue();
                    arrExcelContent[rowNumber][cellNumber] = Byte.toString(cellErrorValue);
                } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                    cellStringValue = cell.getCellFormula();
                    arrExcelContent[rowNumber][cellNumber] = cellStringValue;

                } else {

                    cellDoubleValue = cell.getNumericCellValue();
                    arrExcelContent[rowNumber][cellNumber] = Double.toString(cellDoubleValue);
                }
            }

        }
    } finally {
        if (((InputStream) workbook) != null) {
            ((InputStream) workbook).close();
        }
    }
    return arrExcelContent;
}

From source file:com.wabacus.system.dataimport.filetype.XlsFileProcessor.java

License:Open Source License

private Object getCellValue(Cell cell) {
    if (cell == null)
        return null;
    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
        return cell.getRichStringCellValue().getString();
    case Cell.CELL_TYPE_BOOLEAN:
        return String.valueOf(cell.getBooleanCellValue());
    case Cell.CELL_TYPE_NUMERIC:
        if (DateUtil.isCellDateFormatted(cell)) {
            return cell.getDateCellValue();
        } else {//from w w w .  ja va  2s.co  m
            return String.valueOf(cell.getNumericCellValue());
            /*double d=cell.getNumericCellValue();
            if(d-(int)d<Double.MIN_VALUE)
            { // ?int  
                return (int)d;
            }else
            { 
                return cell.getNumericCellValue();
            }*/
        }
    case Cell.CELL_TYPE_BLANK:
        return "";
    default:
        return null;
    }
}