Example usage for org.apache.poi.hssf.usermodel HSSFRow getPhysicalNumberOfCells

List of usage examples for org.apache.poi.hssf.usermodel HSSFRow getPhysicalNumberOfCells

Introduction

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

Prototype


@Override
public int getPhysicalNumberOfCells() 

Source Link

Document

gets the number of defined cells (NOT number of cells in the actual row!).

Usage

From source file:com.qms.operations.rates.ejb.sls.BuyRatesSessionBean.java

License:Open Source License

public String processExcelDelete(String fileName) throws EJBException {
    String s1 = "";
    PreparedStatement pstmtDetails = null;
    // PreparedStatement pstmtDetails1      = null;Commented by govind on 16-02-2010 for connectionLeakages
    PreparedStatement Details = null;
    // PreparedStatement Details1           = null;Commented by govind on 16-02-2010 for connectionLeakages
    Connection connection = null;
    OperationsImpl operationsImpl = null;
    String deleteDtl = "TRUNCATE TABLE QMS_BUYRATES_DELETE_DETAILS";
    //   String            deleteDtl1         = "DELETE FROM QMS_BUYRATES_DELETE_DATA";
    String queryDetails = "INSERT INTO QMS_BUYRATES_DELETE_DETAILS (ROW_ID,ORIGIN,DESTINATION,CARRIER_ID,SERVICE_LEVEL,FREQUENCY,TRANSIT_TIME,CURRENCY,TERMINAL_ID,DENSITY_CODE) VALUES (?,?,?,?,?,?,?,?,?,?)";
    //   String            queryDetails1     = "INSERT INTO QMS_BUYRATES_DELETE_DATA (ROW_ID,LINE_NO,CONTAINER_NO,CONTAINER_VALUE) VALUES (?,?,?,?)";         

    String msgquery = "SELECT ERROR_MSG FROM QMS_BUYRATES_DELETE_DETAILS";
    //   ResultSet         rs               = null;Commeneted by Govind on 16-02-2010 for Connection Leakages
    String returnstr = null;/*ww w  .ja v  a2  s. c  o  m*/
    CallableStatement cstmt = null;
    try {
        String s = "";
        String mainHeaderData[] = new String[8];
        int rows = 0;
        int cols = 0;
        int notesIndex = 0;
        int batchCount = 0;
        HSSFRow row = null;
        HSSFCell cell = null;
        InputStream myxls = new FileInputStream(fileName);
        HSSFWorkbook wb = new HSSFWorkbook(myxls);
        HSSFSheet sheet = wb.getSheetAt(0);
        rows = sheet.getPhysicalNumberOfRows();
        //   connection=ConnectionUtil.getConnection();
        operationsImpl = new OperationsImpl();
        connection = operationsImpl.getConnection();
        Details = connection.prepareStatement(deleteDtl);

        Details.execute();

        //  Details1 = connection.prepareStatement(deleteDtl1);
        //  Details1.execute();
        row = sheet.getRow(0);

        cols = row.getPhysicalNumberOfCells();

        int l = cols - 1;

        for (; l >= 0; l--) {
            cell = row.getCell((short) l);

            if ("TERMINALID:".equalsIgnoreCase(getCellData(cell, 0)))
                break;

        }

        notesIndex = l + 1;
        //  notesIndex=cols;

        String detailsData[] = new String[notesIndex];
        /*String containersData[] =new String[notesIndex-7];
        for(l=7;l<notesIndex-2;l++)
        {
           cell=row.getCell((short)l);
           containersData[l-7]=getCellData(cell);
        }*/

        pstmtDetails = connection.prepareStatement(queryDetails);

        //  pstmtDetails1= connection.prepareStatement(queryDetails1);

        for (int i = 1; i < rows; i++) {

            row = sheet.getRow(i);
            double time = 0.0;
            String data = null;
            for (int j = 0; j < notesIndex; j++) {
                if (row != null) {
                    cell = row.getCell((short) j);

                    /* {
                     cell.setCellType(cell.CELL_TYPE_STRING);
                            
                     }*/
                    detailsData[j] = getCellData(cell, 0);
                    if (j == 4) // Added by Gowtham.
                    {
                        if (detailsData[j].toString().indexOf(".") != -1)
                            detailsData[j] = detailsData[j].substring(0,
                                    detailsData[j].toString().indexOf("."));
                    }
                    if (j == 6 && (cell.CELL_TYPE_NUMERIC == cell.getCellType())
                            && (detailsData[j].indexOf(".") != -1) && (Double.parseDouble(
                                    detailsData[j].substring(0, detailsData[j].indexOf("."))) < 1)) {
                        time = 1 / Double.parseDouble(detailsData[j]);
                        Double t = new Double(time);
                        if (t.toString().indexOf(".") != -1) {
                            data = t.toString().substring(0, t.toString().indexOf("."));
                        }
                        if (data != null) {
                            detailsData[j] = data + ":" + "00";
                        }
                    }
                    if (j == 6 && (cell.CELL_TYPE_NUMERIC == cell.getCellType())
                            && (detailsData[j].indexOf(".") != -1) && (!(Double.parseDouble(
                                    detailsData[j].substring(0, detailsData[j].indexOf("."))) < 1))) {
                        if (detailsData[j].indexOf(".") != -1) {
                            detailsData[j] = detailsData[j].substring(0, detailsData[j].indexOf("."));
                        }

                    }
                    if (j == 5 && detailsData[j].indexOf(".") != -1) {
                        detailsData[j] = detailsData[j].substring(0, detailsData[j].indexOf("."));
                    }
                    /*if(j==8&&detailsData[j].indexOf(".")!=-1)
                    {
                       detailsData[j] =detailsData[j].substring(0, detailsData[j].indexOf("."));
                      }*/
                }
            }
            batchCount++;

            insertDeleteDetails(detailsData, pstmtDetails, notesIndex, i);

            if (batchCount == 150) {
                pstmtDetails.executeBatch();
                pstmtDetails.clearBatch();

                batchCount = 0;

            }
        }

        if (batchCount > 0) {
            pstmtDetails.executeBatch();
            pstmtDetails.clearBatch();

            batchCount = 0;
        }

        cstmt = connection.prepareCall("{ ?=call QMS_BUY_RATES_UPLOAD_PKG.BUY_RATES_DELETE_PROC}");

        cstmt.registerOutParameter(1, Types.VARCHAR);
        cstmt.execute();
        returnstr = (String) cstmt.getString(1);

        //End
        return returnstr;
    } catch (Exception e) {
        logger.error("Exception");
        e.printStackTrace();
    } finally {
        try {
            /*    if(rs!=null)
               rs.close();-*/
            //Commented by govind  on 16-02-2010 fro connection leakages.

            if (pstmtDetails != null)
                pstmtDetails.close();
            if (Details != null)
                Details.close();
            if (cstmt != null)
                cstmt.close();
            if (connection != null)
                connection.close();
        } catch (Exception e) {
            logger.error("Error Occured  while closing Resources" + e);
        }
    }

    return s1;
}

From source file:com.util.tools.FeraExporter.java

public void postProcessXLS(Object document) {
    HSSFWorkbook wb = (HSSFWorkbook) document;
    HSSFSheet sheet = wb.getSheetAt(0);/*from  w ww . j a  v a 2  s .c  o m*/
    HSSFRow header = sheet.getRow(0);

    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setFillForegroundColor(HSSFColor.BLUE_GREY.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

    for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
        HSSFCell cell = header.getCell(i);

        cell.setCellStyle(cellStyle);
    }
}

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

License:Open Source License

/**
 * Fills badHeads with indexes for columns that contain data but don't have a header or have an non-string header (because it makes things difficult with HSSF).
 * Fills emptyCols with indexes for columns that are totally empty.
 * Assumes that badHeads and emptyCols are not null and empty.
 * //from w w w.  j av a 2s. c  o m
 */
public void checkHeadsAndCols(final HSSFSheet sheet, Vector<Integer> badHeads, Vector<Integer> emptyCols) {
    boolean firstRow = true;
    Vector<Boolean> firstRowCells = new Vector<Boolean>();
    Vector<Boolean> restCells = new Vector<Boolean>();

    // Iterate over each row in the sheet
    Iterator<?> rows = sheet.rowIterator();
    while (rows.hasNext()) {
        HSSFRow row = (HSSFRow) rows.next();
        int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum());
        for (int col = 0; col < maxSize; col++) {
            if (firstRow) {
                if (row.getCell(col) == null) {
                    firstRowCells.add(false);
                } else if (row.getCell(col).getCellType() == HSSFCell.CELL_TYPE_STRING) {
                    firstRowCells.add(true);
                } else {
                    firstRowCells.add(null);
                }
            } else {
                if (col == restCells.size()) {
                    restCells.add(false);
                }
                if (!restCells.get(col)) {
                    restCells.set(col, row.getCell(col) != null);
                }
            }
        }
        firstRow = false;
    }

    //pad smaller vector with false if necessary.
    while (restCells.size() < firstRowCells.size()) {
        restCells.add(false);
    }
    while (firstRowCells.size() < restCells.size()) {
        firstRowCells.add(false);
    }

    for (int c = 0; c < firstRowCells.size(); c++) {
        if (firstRowCells.get(c) == null || (!firstRowCells.get(c) && restCells.get(c))) {
            badHeads.add(c);
        }
        if (firstRowCells.get(c) != null && !firstRowCells.get(c) && !restCells.get(c)) {
            emptyCols.add(c);
        }
    }
}

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

License:Open Source License

@Override
protected void nonInteractiveConfig() {
    try {/*from   ww w .j  a  va 2s.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;
    }
}

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

License:Open Source License

/**
 * Parses the given import xls file according to the users selection and creates/updates the
 * Preview table, showing the user how the import options effect the way the data will be
 * imported into the spreadsheet./*ww w . java 2 s . c  o m*/
 * 
 * @param table - the table to display the data
 * @return JTable - the table to display the data
 */
private JTable setXLSTableData(final JTable table) {
    int numRows = 0;
    int numCols = 0;
    String[] headers = {};
    Vector<Vector<String>> tableDataVector = new Vector<Vector<String>>();
    Vector<String> rowData = new Vector<String>();
    Vector<String> headerVector = new Vector<String>();
    DateWrapper scrDateFormat = AppPrefsCache.getDateWrapper("ui", "formatting", "scrdateformat");
    try {
        log.debug("setXLSTableData - file - " + configXLS.getFile().toString());

        InputStream input = new FileInputStream(configXLS.getFile());
        POIFSFileSystem fs = new POIFSFileSystem(input);
        HSSFWorkbook workBook = new HSSFWorkbook(fs);
        HSSFSheet sheet = workBook.getSheetAt(0);

        Vector<Integer> badHeads = new Vector<Integer>();
        Vector<Integer> emptyCols = new Vector<Integer>();
        ((ConfigureXLS) config).checkHeadsAndCols(sheet, badHeads, emptyCols);
        if (badHeads.size() > 0 && doesFirstRowHaveHeaders) {
            if (table != null) {
                ((ConfigureXLS) config).showBadHeadingsMsg(badHeads, emptyCols, getTitle());
            }
            this.doesFirstRowHaveHeaders = false;
            try {
                ignoreActions = true;
                this.containsHeaders.setSelected(false);
            } finally {
                ignoreActions = false;
            }
            if (table != null) {
                return table;
            }
        }
        boolean firstRow = true;

        //quick fix to prevent ".0" at end of catalog numbers etc
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(0);
        nf.setMaximumFractionDigits(20);
        nf.setGroupingUsed(false); //gets rid of commas

        int maxCols = 0;

        // Iterate over each row in the sheet
        Iterator<?> rows = sheet.rowIterator();
        while (rows.hasNext()) {
            numCols = 0;
            rowData = new Vector<String>();
            HSSFRow row = (HSSFRow) rows.next();
            //log.debug(row.getLastCellNum()+"  "+row.getPhysicalNumberOfCells());
            int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum());
            if (maxSize > maxCols) {
                maxCols = maxSize;
            }
            while (numCols < maxSize) {
                if (emptyCols.indexOf(new Integer(numCols)) == -1) {
                    HSSFCell cell = row.getCell(numCols);
                    String value = null;
                    // if cell is blank, set value to ""
                    if (cell == null) {
                        value = "";
                    } else {
                        int type = cell.getCellType();

                        switch (type) {
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            // The best I can do at this point in the app is to guess if a
                            // cell is a date.
                            // Handle dates carefully while using HSSF. Excel stores all
                            // dates as numbers, internally.
                            // The only way to distinguish a date is by the formatting of
                            // the cell. (If you
                            // have ever formatted a cell containing a date in Excel, you
                            // will know what I mean.)
                            // Therefore, for a cell containing a date, cell.getCellType()
                            // will return
                            // HSSFCell.CELL_TYPE_NUMERIC. However, you can use a utility
                            // function,
                            // HSSFDateUtil.isCellDateFormatted(cell), to check if the cell
                            // can be a date.
                            // This function checks the format against a few internal
                            // formats to decide the issue,
                            // but by its very nature it is prone to false negatives.
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue());
                                //value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue());
                            } else {
                                double numeric = cell.getNumericCellValue();
                                value = nf.format(numeric);
                            }
                            break;

                        case HSSFCell.CELL_TYPE_STRING:
                            value = cell.getRichStringCellValue().getString();
                            break;

                        case HSSFCell.CELL_TYPE_BLANK:
                            value = "";
                            break;

                        case HSSFCell.CELL_TYPE_BOOLEAN:
                            value = Boolean.toString(cell.getBooleanCellValue());
                            break;

                        case HSSFCell.CELL_TYPE_FORMULA:
                            value = UIRegistry.getResourceString("WB_FORMULA_IMPORT_NO_PREVIEW");
                            break;

                        default:
                            value = "";
                            log.error("unsuported cell type");
                            break;
                        }
                    }
                    if (firstRow && doesFirstRowHaveHeaders) {
                        checkUserColInfo(value, numCols);
                    }
                    if (isUserCol(numCols)) {
                        rowData.add(value.toString());
                    }
                }
                numCols++;
            }
            if (doesFirstRowHaveHeaders && firstRow) {
                headerVector = rowData;
                headers = new String[rowData.size()];
            } else if (!doesFirstRowHaveHeaders && firstRow) {
                //headers = createDummyHeaders(rowData.size());
                tableDataVector.add(rowData);
            } else {
                tableDataVector.add(rowData);
            }
            firstRow = false;
            numRows++;
        }
        maxCols -= emptyCols.size();
        if (!doesFirstRowHaveHeaders) {
            headerVector = createDummyHeadersAsVector(maxCols);
            headers = new String[maxCols];
        }
        for (int i = 0; i < headerVector.size(); i++) {
            headers[i] = headerVector.elementAt(i);
        }
        printArray(headers);

        String[][] tableData = new String[tableDataVector.size()][maxCols];
        for (int i = 0; i < tableDataVector.size(); i++) {
            Vector<String> v = tableDataVector.get(i);
            for (int j = 0; j < v.size(); j++) {
                tableData[i][j] = v.get(j).toString();
            }

        }
        if (checkForErrors(headers, tableData)) {
            errorPanel.showDataImportStatusPanel(true);
        } else {
            errorPanel.showDataImportStatusPanel(false);
        }

        if ((doesFirstRowHaveHeaders ? numRows - 1 : numRows) > WorkbenchTask.MAX_ROWS) {
            hasTooManyRows = true;
            showTooManyRowsErrorDialog();
        } else {
            hasTooManyRows = false;
        }
        log.debug(headers);
        log.debug(tableData);
        model = new PreviewTableModel(headers, tableData);
        JTable result = null;
        if (table == null) {
            result = new JTable();
            result.setColumnSelectionAllowed(false);
            result.setRowSelectionAllowed(false);
            result.setCellSelectionEnabled(false);
            result.getTableHeader().setReorderingAllowed(false);
            result.setPreferredScrollableViewportSize(new Dimension(500, 100));
            result.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        } else {
            result = table;
        }
        result.setModel(model);
        result.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
        model.fireTableDataChanged();
        model.fireTableStructureChanged();
        return result;
    } catch (Exception ex) {
        UIRegistry.displayErrorDlgLocalized(UIRegistry.getResourceString("WB_ERROR_READING_IMPORT_FILE"));
        if (table != null) {
            String[] columnNames = {};
            String[][] blankData = { {} };
            model = new PreviewTableModel(columnNames, blankData);
            table.setModel(model);
            table.setColumnSelectionAllowed(false);
            table.setRowSelectionAllowed(false);
            table.setCellSelectionEnabled(false);
            table.getTableHeader().setReorderingAllowed(false);
            table.setPreferredScrollableViewportSize(new Dimension(500, 100));
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
            model.fireTableDataChanged();
            model.fireTableStructureChanged();
            return table;
        }
        //log.error("Error attempting to parse input xls file:" + ex);
        //ex.printStackTrace();
    }

    return null;
}

From source file:edu.wustl.catissuecore.webservice.util.ExcelFileReader.java

License:BSD License

/**
 * Method to read content of one row of Excel sheet
 * @param row HSSFRow row whose content to be read
 * @return/*from   w  w w  .ja  v a 2s.c  o  m*/
 */
private String[] getRowContent(HSSFRow row) {
    HSSFCell cell = null;
    int noOfColumn = row.getPhysicalNumberOfCells();
    String[] rowContent = new String[noOfColumn];
    for (short i = 0; i < noOfColumn; i++) {
        try {
            cell = row.getCell(i);
            if (cell == null)
                rowContent[i] = "";
            else {
                if (columnDataType.length > i && columnDataType[i] != null) {
                    switch (columnDataType[i]) {
                    case 0: {
                        HSSFRichTextString strCell = cell.getRichStringCellValue();
                        rowContent[i] = strCell.toString();
                        break;
                    }
                    case 1: {
                        rowContent[i] = String.valueOf(cell.getNumericCellValue());
                        break;
                    }
                    case 2: {
                        Date date = cell.getDateCellValue();
                        rowContent[i] = parseDateToString(date, DATE_PATTERN_MM_DD_YYYY);
                        break;
                    }
                    }
                } else {
                    HSSFRichTextString strCell = cell.getRichStringCellValue();
                    rowContent[i] = strCell.toString();
                }
            }
        } catch (Exception e) {
            System.out.println("columnDataType[" + i + "]" + columnDataType[i]);
        }
    }
    return rowContent;
}

From source file:file.open.util.parse.XlsParser.java

License:Open Source License

public String[] splitLine() throws Exception {
    if (m_iCurrentRow == m_iNbRows) {
        return null;
    }//ww  w .  j a va 2 s  . c  o m

    HSSFRow row = m_sheet.getRow(m_iCurrentRow);
    if (row == null) {
        return null;
    } else {
        int cellIndex = 0;
        int noOfCells = row.getPhysicalNumberOfCells();
        String[] values = new String[noOfCells];
        short firstCellNum = row.getFirstCellNum();
        short lastCellNum = row.getLastCellNum();

        if (firstCellNum >= 0 && lastCellNum >= 0) {
            for (short iCurrent = firstCellNum; iCurrent < lastCellNum; iCurrent++) {
                HSSFCell cell = (HSSFCell) row.getCell((int) iCurrent);
                if (cell == null) {
                    values[iCurrent] = "";
                    cellIndex++;
                    continue;
                } else {
                    switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        double value = cell.getNumericCellValue();
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            if (HSSFDateUtil.isValidExcelDate(value)) {
                                Date date = HSSFDateUtil.getJavaDate(value);
                                SimpleDateFormat dateFormat = new SimpleDateFormat(JAVA_TOSTRING);
                                values[iCurrent] = dateFormat.format(date);
                            } else {
                                throw new Exception("Invalid Date value found at row number " + row.getRowNum()
                                        + " and column number " + cell.getNumericCellValue());
                            }
                        } else {
                            values[iCurrent] = value + "";
                        }
                        break;

                    case HSSFCell.CELL_TYPE_STRING:
                        values[iCurrent] = cell.getStringCellValue();
                        break;

                    case HSSFCell.CELL_TYPE_BLANK:
                        values[iCurrent] = null;
                        break;

                    default:
                        values[iCurrent] = null;
                    }
                }
            }
        }
        m_iCurrentRow++;
        return values;
    }

}

From source file:gov.nih.nci.evs.browser.utils.ExcelUtil.java

License:Open Source License

public static String getHSSFHeader(String file, int sheet) {
    StringBuffer buf = new StringBuffer();
    try {//www. j a  va2s  . c  om
        FileInputStream fis = new FileInputStream(new File(file));
        //Get the workbook instance for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(fis);
        try {
            fis.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //Get first sheet from the workbook
        HSSFSheet hSSFSheet = workbook.getSheetAt(sheet);
        HSSFRow row = hSSFSheet.getRow(0);

        int cells = row.getPhysicalNumberOfCells();
        for (int c = 0; c < cells; c++) {
            HSSFCell cell = row.getCell(c);
            String value = null;

            switch (cell.getCellType()) {

            case HSSFCell.CELL_TYPE_FORMULA:
                value = cell.getCellFormula();
                break;

            case HSSFCell.CELL_TYPE_NUMERIC:
                value = "" + cell.getNumericCellValue();
                break;

            case HSSFCell.CELL_TYPE_STRING:
                value = cell.getStringCellValue();
                break;

            default:
            }
            buf.append(value);
            if (c < cells - 1) {
                buf.append("|");
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return buf.toString();
}

From source file:include.excel_import.XlsInfo.java

License:Open Source License

/**
 * SHEET/*from   w  ww .j  a  v a2  s  .  co m*/
 * @param sheet HSSFSheet
 * @return int 
 */
public int getColumnCount(String sheetName) {
    if (columnCount.containsKey(sheetName)) {
        return ((Integer) columnCount.get(sheetName)).intValue();
    }
    HSSFSheet sheet = getSheetForSheetName(sheetName);
    HSSFRow row = sheet.getRow(0);
    int size = 0;
    int cellssize = row.getPhysicalNumberOfCells();
    for (int i = 0; i < cellssize; i++) {
        HSSFCell cell = row.getCell((short) i);
        if (cell != null) {
            size++;
            cell = null;
        } // end of if ()
    }
    Integer mysize = new Integer(size);
    columnCount.put(sheetName, mysize);
    sheet = null;
    row = null;
    mysize = null;
    //System.gc();
    return size;
}

From source file:include.excel_import.XlsInfo.java

License:Open Source License

public Vector getColumnsName(String sheetName) {
    if (columnsNames.containsKey(sheetName)) {
        return (Vector) columnsNames.get(sheetName);
    }//from  w ww  . j a  v a 2  s .c  om
    HSSFSheet sheet = getSheetForSheetName(sheetName);
    getColumnsName_result.clear();
    HSSFRow row = sheet.getRow((short) 0);
    int cellssize = row.getPhysicalNumberOfCells();
    for (int i = 0; i < cellssize; i++) {
        HSSFCell cell = row.getCell((short) i);
        getColumnsName_result.addElement(cell.getStringCellValue());
        cell = null;
    }
    columnsNames.put(sheetName, getColumnsName_result);
    sheet = null;
    row = null;

    //System.gc();
    return getColumnsName_result;
}