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

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the cell This method returns a simple representation, anything more complex should be in user code, with knowledge of the semantics of the sheet being processed.

Usage

From source file:guineu.data.parser.impl.LCMSParserXLS.java

License:Open Source License

public void fillData() {
    try {//from   ww w  . j  av a 2s. co  m
        book = this.openExcel(DatasetName);
        HSSFSheet sheet;
        try {
            sheet = book.getSheet(sheetName);
        } catch (Exception exception) {
            sheet = book.getSheetAt(0);
        }

        int initRow = this.getRowInit(sheet);

        if (initRow > -1) {
            numberRows = this.getNumberRows(initRow, sheet);
            HSSFRow row = sheet.getRow(initRow);

            for (int i = 0; i < row.getLastCellNum(); i++) {
                HSSFCell cell = row.getCell((short) i);
                this.head.add(cell.toString());
            }
            this.readLipids(initRow + 1, numberRows, sheet);

            this.setExperimentsName(head);
        } else {
            this.dataset = null;
        }
    } catch (IOException ex) {
        Logger.getLogger(LCMSParserXLS.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:guineu.data.parser.impl.LCMSParserXLS.java

License:Open Source License

/**
 * Reads lipid information of one row.//from  ww w.  ja v  a  2 s .c o  m
 * @param row
 * @param numberCols
 * @return
 */
public void readRow(HSSFRow row) {
    HSSFCell cell;
    SimplePeakListRowLCMS lipid = new SimplePeakListRowLCMS();
    for (int i = 0; i < row.getLastCellNum(); i++) {
        try {
            String title = head.get(i);
            if (title == null) {
                continue;
            }
            cell = row.getCell((short) i);
            boolean isfound = false;
            for (LCMSColumnName field : LCMSColumnName.values()) {
                if (title.matches(field.getRegularExpression())) {
                    if (field == LCMSColumnName.RT) {
                        double rt = cell.getNumericCellValue();
                        if (rt < 20) {
                            rt *= 60;
                            lipid.setVar(field.getSetFunctionName(), rt);
                        } else {
                            lipid.setVar(field.getSetFunctionName(), cell.getNumericCellValue());
                        }
                    } else {
                        lipid.setVar(field.getSetFunctionName(),
                                this.getType(cell.toString(), field.getType()));
                    }
                    isfound = true;
                    break;
                }
            }

            if (!isfound) {
                try {
                    lipid.setPeak(title, cell.getNumericCellValue());
                } catch (Exception e) {
                    if (cell.toString().matches(".*null.*|.*NA.*|.*N/A.*")) {
                        lipid.setPeak(title, 0.0);
                    } else if (cell.toString() != null) {
                        lipid.setPeak(title, cell.toString());
                    }
                }
            }

            if (i == 0 && (cell.getCellStyle().getFillForegroundColor() == 13)) {
                lipid.setStandard(1);
            }
            int DataType = this.v_type(book, row, cell);
            if (DataType == 0) {
                lipid.setControl(false);
                lipid.setName("z-non valid");
            } else {
                lipid.setControl(true);
            }

            if (lipid.getName() == null) {
                lipid.setName("unknown");
            }
            lipid.setLipidClass(String.valueOf(this.LipidClassLib.get_class(lipid.getName())));
        } catch (Exception exception) {
            //exception.printStackTrace();
        }
    }
    this.dataset.addRow(lipid);
}

From source file:guineu.data.parser.impl.LCMSParserXLS.java

License:Open Source License

/**
 *
 * @param sheet/*from   w ww. j a  v  a  2 s.  c om*/
 * @return number of row which it starts to read the excel file.
 */
public int getRowInit(HSSFSheet sheet) {

    Iterator rowIt = sheet.rowIterator();
    int num = -1;

    while (rowIt.hasNext()) {
        HSSFRow row = (HSSFRow) rowIt.next();
        HSSFCell cell = row.getCell((short) 0);

        if (cell != null) {
            for (LCMSColumnName field : LCMSColumnName.values()) {
                if (cell.toString().matches(field.getRegularExpression())) {
                    num = row.getRowNum();
                    break;
                }
            }
        }
    }

    return num;
}

From source file:guineu.data.parser.impl.ParserXLS.java

License:Open Source License

public int v_type(HSSFWorkbook wb, HSSFRow row, HSSFCell cell) {
    switch (cell.getCellType()) {
    case HSSFCell.CELL_TYPE_BLANK:
        System.out.println(" Error - Row: " + row.getRowNum() + " Cell: " + cell.getColumnIndex()
                + "  - Cell type Blank  - " + cell.toString());
        return 0;
    case HSSFCell.CELL_TYPE_BOOLEAN:
        System.out.println(" Error - Row: " + row.getRowNum() + " Cell: " + cell.getColumnIndex()
                + "  - Cell type boolean  - " + cell.toString());
        return 0;
    case HSSFCell.CELL_TYPE_FORMULA:
        System.out.println(" Error - Row: " + row.getRowNum() + " Cell: " + cell.getColumnIndex()
                + "  - Cell type formula  - " + cell.toString());
        return 1;
    case HSSFCell.CELL_TYPE_NUMERIC:
        HSSFCellStyle style = cell.getCellStyle();
        HSSFFont font = wb.getFontAt(style.getFontIndex());
        if (font.getColor() == (new HSSFColor.RED().getIndex())) {
            return 0;
        }/*from w ww  .  j a  va  2  s  . com*/
        return 1;
    case HSSFCell.CELL_TYPE_STRING:
        style = cell.getCellStyle();
        font = wb.getFontAt(style.getFontIndex());
        if (font.getColor() == (new HSSFColor.RED().getIndex())) {
            return 0;
        }
        return 2;
    default:
        return 0;
    }
}

From source file:guineu.modules.configuration.parameters.ParameterDialog.java

License:Open Source License

public void readRows(HSSFSheet sheet) {
    try {//from www .  j  ava2s.  com
        Iterator rowIt = sheet.rowIterator();
        HSSFRow row = (HSSFRow) rowIt.next();

        for (int i = 1; i < row.getLastCellNum(); i++) {
            HSSFCell cell = row.getCell(i);
            model.addColumn(cell.toString());
        }
        ((ParameterDataModel) model).fireTableStructureChanged();
        table.getColumnModel().getColumn(0).setMinWidth(300);
        int rowIndex = -1;
        while (rowIt.hasNext()) {
            row = (HSSFRow) rowIt.next();
            HSSFCell cell;
            cell = row.getCell(0);
            for (int e = 0; e < model.getRowCount(); e++) {
                String sampleName = model.getValueAt(e, 0);
                if (sampleName.equals(cell.toString())) {
                    rowIndex = e;
                }
            }
            for (int i = 1; i < row.getLastCellNum(); i++) {
                cell = row.getCell(i);
                model.setValueAt(cell.toString(), rowIndex, i);
            }
        }
        ((ParameterDataModel) model).addParameters(dataset);
        ((ParameterDataModel) model).fireTableDataChanged();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:javaapplication2.Frame1.java

void fillData(File file) {
    int index = -1;
    HSSFWorkbook workbook = null;//from  w  w w .  j av a  2s .  c  o  m
    try {
        try {
            FileInputStream inputStream = new FileInputStream(file);
            workbook = new HSSFWorkbook(inputStream);
        } catch (IOException ex) {
            Logger.getLogger(Frame1.class.getName()).log(Level.SEVERE, null, ex);
        }

        String[] strs = new String[workbook.getNumberOfSheets()];
        //get all sheet names from selected workbook
        for (int i = 0; i < strs.length; i++) {
            strs[i] = workbook.getSheetName(i);
        }
        JFrame frame = new JFrame("Input Dialog");

        String selectedsheet = (String) JOptionPane.showInputDialog(frame,
                "Which worksheet you want to import ?", "Select Worksheet", JOptionPane.QUESTION_MESSAGE, null,
                strs, strs[0]);

        if (selectedsheet != null) {
            for (int i = 0; i < strs.length; i++) {
                if (workbook.getSheetName(i).equalsIgnoreCase(selectedsheet))
                    index = i;
            }
            HSSFSheet sheet = workbook.getSheetAt(index);
            HSSFRow row = sheet.getRow(0);

            headers.clear();
            //int value=row.getLastCellNum();
            for (int i = 0; i < row.getLastCellNum(); i++) {
                HSSFCell cell1 = row.getCell(i);
                headers.add(cell1.toString());

            }

            data.clear();
            for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
                Vector d = new Vector();
                row = sheet.getRow(j);
                int noofrows = row.getLastCellNum();
                for (int i = 0; i < noofrows; i++) { //To handle empty excel cells 
                    HSSFCell cell = row.getCell(i, org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK);
                    d.add(cell.toString());
                }
                d.add("\n");
                data.add(d);
            }
        } else {
            return;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:javaexecelprocess.JavaExecelProcess.java

public void insertDataFromExcel() {
    String templateInsert = "INSERT INTO `mytbl1` (`id`, `myf1`, `myf2`) VALUES (NULL, 'h111', 'h222');";
    //        String templateInsert = "INSERT INTO `mytbl1` (`id`, `myf1`, `myf2`) VALUES ('2', 'h111', 'h222');";
    String sqlHead = "";
    sqlHead += "INSERT INTO `" + fields.get(0) + "` (`id`,";
    int i = 0;//www  .  j  a va  2s  . c  o m
    for (i = 0; i < fields.size() - 2; i++) {
        sqlHead += " `" + fields.get(i + 1) + "`,";
    }
    sqlHead += " `" + fields.get(i + 1) + "`) VALUES (NULL,";

    PreparedStatement pst = null;
    HSSFSheet activeSheet = wb.getSheetAt(0);
    int iFirstRow = activeSheet.getFirstRowNum();
    int iLastRow = activeSheet.getLastRowNum();
    for (i = iFirstRow + 1; i <= iLastRow; i++) {
        String sql = sqlHead;
        HSSFRow row = activeSheet.getRow(i);
        int iFirstCol = row.getFirstCellNum();
        int iLastCol = row.getLastCellNum();
        int j = 0;
        for (j = iFirstCol; j < iLastCol - 1; j++) {
            HSSFCell cell = row.getCell(j);
            String cessStr = cell.toString();
            sql += " '" + cessStr + "',";
        }
        HSSFCell cell = row.getCell(j);
        String cessStr = cell.toString();
        sql += " '" + cessStr + "');";
        try {
            pst = mysqlConn.prepareStatement(sql);
            pst.execute();
        } catch (SQLException ex) {
            Logger.getLogger(JavaExecelProcess.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("insert data exception.");
        }
    }
    //        sql += "INSERT INTO `mytbl1` (`id`, `myf1`, `myf2`) VALUES (NULL, 'f1111', 'f2222');";

}

From source file:Login.ventas.fpagosvarios.java

/**
 * This method is used to print the cell data to the console.
 * @param cellDataList - List of the data's in the spreadsheet.
 */// w w w . j  a  va  2 s .  c o m
private void printToConsole(List cellDataList) {
    for (Object cellDataList1 : cellDataList) {
        List cellTempList = (List) cellDataList1;
        for (Object cellTempList1 : cellTempList) {
            HSSFCell hssfCell = (HSSFCell) cellTempList1;
            String stringCellValue = hssfCell.toString();
            System.out.print(stringCellValue + "\t");
        }
        System.out.println();
    }
}

From source file:net.intelliant.marketing.ContactListServices.java

License:Open Source License

@SuppressWarnings("unchecked")
private static GenericValue insertIntoConfiguredCustomEntity(GenericDelegator delegator, Locale locale,
        String userLoginId, String entityName, HSSFRow excelRowData, Map<String, Object> columnMapper,
        Map<Integer, String> errorDetails) throws GenericEntityException, ParseException {
    ModelEntity modelEntity = delegator.getModelEntity(entityName);
    String entityPrimaryKeyField = modelEntity.getFirstPkFieldName();
    String entityPrimaryKey = delegator.getNextSeqId(entityName);
    GenericValue rowToInsertGV = delegator.makeValue(entityName);
    rowToInsertGV.put(entityPrimaryKeyField, entityPrimaryKey);
    rowToInsertGV.put("importedOnDateTime", UtilDateTime.nowTimestamp());
    rowToInsertGV.put("importedByUserLogin", userLoginId);

    boolean isErrorFound = false;

    Set<Entry<String, Object>> entries = columnMapper.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String columnName = entry.getKey();
        ModelField modelField = modelEntity.getField(columnName);
        HSSFCell excelCell = null;
        Object cellValue = null;//  w w w . ja  v a2  s . com
        short columnIndex = -1;
        try {
            columnIndex = Short.parseShort(String.valueOf(entry.getValue()));
            excelCell = excelRowData.getCell(columnIndex);
            cellValue = (excelCell != null) ? excelCell.toString() : "";
        } catch (NumberFormatException nfe) {
            cellValue = "";
        }
        if (Debug.infoOn()) {
            Debug.logInfo(
                    "[insertIntoConfiguredCustomEntity] Checking excel row No. >> " + excelRowData.getRowNum(),
                    MODULE);
            Debug.logInfo("[insertIntoConfiguredCustomEntity] Checking excel columnIndex >> " + columnIndex,
                    MODULE);
            if (excelCell != null) {
                Debug.logInfo("[insertIntoConfiguredCustomEntity] Checking excel column type >> "
                        + excelCell.getCellType(), MODULE);
            } else {
                Debug.logInfo("[insertIntoConfiguredCustomEntity] excelCell found NULL for columnIndex >> "
                        + columnIndex, MODULE);
            }
            Debug.logInfo("[insertIntoConfiguredCustomEntity] Checking model field >> " + modelField.getName(),
                    MODULE);
            Debug.logInfo("[insertIntoConfiguredCustomEntity] Initial cellValue >> " + cellValue, MODULE);
        }
        if (modelField.getIsNotNull()) {
            if (!UtilValidate.isNotEmpty(cellValue)) {
                Map<String, Object> messageMap = UtilMisc.toMap("columnName", modelField.getDescription());
                errorDetails.put((int) columnIndex,
                        UtilProperties.getMessage(resource, "ErrorImportMapperIsEmpty", messageMap, locale));
                isErrorFound = true;
            }
        }

        if (modelField.getType().equals("email")) {
            if (!(UtilValidate.isNotEmpty(cellValue)
                    && UtilCommon.isValidEmailAddress(String.valueOf(cellValue)))) {
                Map<String, Object> messageMap = UtilMisc.toMap("columnName", cellValue);
                errorDetails.put((int) columnIndex, UtilProperties.getMessage(resource,
                        "ErrorImportMapperNotValidEmail", messageMap, locale));
                isErrorFound = true;
            }
        } else if (modelField.getType().equals("tel-number")) {
            if (UtilValidate.isNotEmpty(cellValue)) {
                Map<String, Object> messageMap = UtilMisc.toMap("columnName", cellValue);
                if (excelCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                    if (Debug.infoOn()) {
                        Debug.logInfo("[insertIntoConfiguredCustomEntity] Cell type is numeric", MODULE);
                    }
                    NumberFormat testNumberFormat = NumberFormat.getNumberInstance();
                    try {
                        cellValue = (pattern.parse(testNumberFormat.format(excelCell.getNumericCellValue())))
                                .longValue();
                    } catch (ParseException e) {
                        errorDetails.put((int) columnIndex, UtilProperties.getMessage(resource,
                                "ErrorImportMapperNotValidPhoneNO", messageMap, locale));
                        isErrorFound = true;
                    }
                }
                if (!UtilValidate.isInternationalPhoneNumber(String.valueOf(cellValue))) {
                    errorDetails.put((int) columnIndex, UtilProperties.getMessage(resource,
                            "ErrorImportMapperNotValidPhoneNO", messageMap, locale));
                    isErrorFound = true;
                }
            }
        } else if (modelField.getType().equals("date")) {
            try {
                cellValue = new java.sql.Date(excelCell.getDateCellValue().getTime());
            } catch (Exception e) {
                cellValue = excelCell.toString();
                Map<String, Object> messageMap = UtilMisc.toMap("columnName", cellValue);
                errorDetails.put((int) columnIndex, UtilProperties.getMessage(resource,
                        "ErrorImportMapperNotValidDate", messageMap, locale));
                isErrorFound = true;
            }
            if (!UtilValidate.isNotEmpty(cellValue)) {
                Map<String, Object> messageMap = UtilMisc.toMap("columnName", cellValue);
                errorDetails.put((int) columnIndex, UtilProperties.getMessage(resource,
                        "ErrorImportMapperNotValidDate", messageMap, locale));
                isErrorFound = true;
            }
        }
        if (Debug.infoOn()) {
            Debug.logInfo("[insertIntoConfiguredCustomEntity] Final cellValue >> " + cellValue, MODULE);
        }
        rowToInsertGV.put(columnName, cellValue);
    }
    if (isErrorFound) {
        throw new GenericEntityException("Errors found in spread sheet data");
    } else {
        delegator.storeAll(UtilMisc.toList(rowToInsertGV));
    }

    return rowToInsertGV;
}

From source file:net.intelliant.tests.ContactListImportTest.java

License:Open Source License

private String getStringData(HSSFCell cell) {
    if (cell != null) {
        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
            return String.valueOf((int) cell.getNumericCellValue());
        }/*from   w  w w . j av a  2  s  .  c  om*/
        return cell.toString();
    }
    return "";
}