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:Creator.WidgetPanel.java

/**
 * Reads a file and returns a list of strings which contain all the variable
 * names//ww w . jav  a 2 s . co m
 *
 * @param filename
 */
public void readXFile(String filename) {

    try {

        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filename));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row;
        HSSFCell cell;

        int rows; // No of rows
        rows = sheet.getPhysicalNumberOfRows();

        int cols = 0; // No of columns
        int tmp = 0;

        int idCol = -1, idName = -1;
        // This trick ensures that we get the data properly even if it doesn't start from first few rows
        for (int i = 0; i < 1; i++) {
            row = sheet.getRow(i);
            if (row != null) {
                tmp = sheet.getRow(i).getPhysicalNumberOfCells();
                if (tmp > cols) {
                    cols = tmp;
                }
            }

            if (!sheet.getRow(i).getCell(0).toString().equals("io_id")) {
                for (int c = 1; c < cols; c++) {
                    if (sheet.getRow(i).getCell(c).equals("io_id")) {
                        idCol = c;
                        break;
                    }
                }
            } else {
                idCol = 0;
            }
            if (!sheet.getRow(i).getCell(1).toString().equals("io_name")) {
                for (int c = 1; c < cols; c++) {
                    if (sheet.getRow(i).getCell(c).equals("io_name")) {
                        idName = c;
                        break;
                    }
                }
            } else {
                idName = 1;
            }

            if (!sheet.getRow(i).getCell(2).toString().equals("io_station_id")) {
                for (int c = 0; c < cols; c++) {
                    if (sheet.getRow(i).getCell(c).equals("io_station_id")) {
                        stationID = (int) sheet.getRow(1).getCell(c).getNumericCellValue();
                        break;
                    }
                }
            } else {
                stationID = (int) sheet.getRow(1).getCell(2).getNumericCellValue();
            }

        }

        if (idName == -1 || idCol == -1) {
            System.out.println("Could not locate io_name or io_id in excel header");
            return;
        }
        if (stationID == -1) {
            System.out.println("Couldnt locate station id");
            return;
        }

        importedIOVariables = new TreeMap<>();
        int io_id;
        String io_name;

        for (int r = 1; r < rows; r++) {
            row = sheet.getRow(r);
            if (row != null) {

                cell = row.getCell(idCol);
                if (cell != null) {
                    io_id = (int) cell.getNumericCellValue();

                    cell = row.getCell(idName);
                    if (cell != null) {
                        io_name = cell.toString().replace("\"", "");
                        // Read both name and id
                        importedIOVariables.put(io_name, io_id);
                    }
                }

            }
        }

        fs.close();

        mf.loadImportedIos(importedIOVariables, 1, stationID);

    } catch (Exception e) {
        System.out.println("Error reading excel file " + e.getMessage());
    }

}

From source file:data.pkg.ReadWriteExcelFile.java

public static void readXLSFile(String path) throws IOException {

    File excel = new File(path);
    FileInputStream fis = new FileInputStream(excel);
    HSSFWorkbook wb = new HSSFWorkbook(fis);
    HSSFSheet ws = wb.getSheet("Sheet1");

    int rowNum = ws.getLastRowNum() + 1;
    int colNum = ws.getRow(0).getLastCellNum();

    for (int i = 0; i < rowNum; i++) {
        HSSFRow row = ws.getRow(i);//w ww.j  a  va2  s  .  c  o m
        for (int j = 0; j < colNum; j++) {
            HSSFCell cell = row.getCell(j);
            if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

                long value = Long.parseLong(cell.toString());

                if (j == 0) {
                    dataOpen.addDeslocamento(value);
                    System.out.println(value);
                }
                if (j == 1) {
                    dataOpen.addForca(value);
                    System.out.println(value);
                }
            }
        }
    }

}

From source file:de.bund.bfr.knime.openkrise.db.imports.custom.LieferkettenImporterEFSA.java

License:Open Source License

private String getStrVal(HSSFCell cell, int maxChars) {
    String result = null;//w ww  .j  a  v  a  2s. c  o m
    try {
        if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
        } else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
            result = cell.getStringCellValue();
            if (result.equals("."))
                result = null;
        } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC
                || cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
            try {
                double dbl = cell.getNumericCellValue();
                if (Math.round(dbl) == dbl)
                    result = "" + ((int) dbl);
                else
                    result = "" + cell.getNumericCellValue();
            } catch (Exception e) {
                result = cell.getStringCellValue();
            }
        } else {
            result = cell.toString();
        }
        if (result != null) {
            if (result.equals("#N/A")) {
                result = null;
            } else if (result.length() > maxChars) {
                String msg = "string too long (" + result.length() + ") - shortened to " + maxChars
                        + " chars... '" + result + "' -> '" + result.substring(0, maxChars) + "'";
                System.err.println(msg);
                logMessages += msg + "\n";
                result = result.substring(0, maxChars);
            }
        }
    } catch (Exception e) {
    }
    return result;
}

From source file:de.fionera.javamailer.dataProcessors.parseFilesForImport.java

/**
 * Gets a XLS file and parse it//from w  ww.j  av  a2s. co m
 * @param file The XLS File that you want to get parsed
 * @return A ArrayList where the first object is a Array containing the Data and the Second the Header
 */
public ArrayList<Object> parseXLSFile(File file) {
    int index = -1;
    HSSFWorkbook workbook = null;
    try {
        try {
            FileInputStream inputStream = new FileInputStream(file);
            workbook = new HSSFWorkbook(inputStream);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        assert workbook != null;
        String[] strings = new String[workbook.getNumberOfSheets()];
        //get all sheet names from selected workbook
        for (int i = 0; i < strings.length; i++) {
            strings[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,
                strings, strings[0]);

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

            if (row != null) {
                headers = new String[row.getLastCellNum()];

                for (int i = 0; i < row.getLastCellNum(); i++) {
                    headers[i] = row.getCell(i).toString();
                }
            }

            data = new String[sheet.getLastRowNum()][];
            for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
                row = sheet.getRow(j);
                int rowCount = row.getLastCellNum();
                String[] dataRow = new String[rowCount];
                for (int i = 0; i < rowCount; i++) {
                    HSSFCell cell = row.getCell(i, org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK);
                    dataRow[i] = cell.toString();
                }
                data[j - 1] = dataRow;
            }
        } else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    ArrayList<Object> returnData = new ArrayList<>();
    returnData.add(data);
    returnData.add(headers);

    return returnData;
}

From source file:de.sub.goobi.forms.ProzessverwaltungForm.java

License:Open Source License

/**
 * Generate result as PDF./*from  ww  w  .  j a v a  2 s .  c  o  m*/
 */
public void generateResultAsPdf() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {

        /*
         * Vorbereiten der Header-Informationen
         */
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        try {
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
            String contentType = servletContext.getMimeType("search.pdf");
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=\"search.pdf\"");
            ServletOutputStream out = response.getOutputStream();

            SearchResultGeneration sr = new SearchResultGeneration(this.filter, this.showClosedProcesses,
                    this.showArchivedProjects);
            HSSFWorkbook wb = sr.getResult();
            List<List<HSSFCell>> rowList = new ArrayList<>();
            HSSFSheet mySheet = wb.getSheetAt(0);
            Iterator<Row> rowIter = mySheet.rowIterator();
            while (rowIter.hasNext()) {
                HSSFRow myRow = (HSSFRow) rowIter.next();
                Iterator<Cell> cellIter = myRow.cellIterator();
                List<HSSFCell> row = new ArrayList<>();
                while (cellIter.hasNext()) {
                    HSSFCell myCell = (HSSFCell) cellIter.next();
                    row.add(myCell);
                }
                rowList.add(row);
            }
            Document document = new Document();
            Rectangle a4quer = new Rectangle(PageSize.A3.getHeight(), PageSize.A3.getWidth());
            PdfWriter.getInstance(document, out);
            document.setPageSize(a4quer);
            document.open();
            if (rowList.size() > 0) {
                Paragraph p = new Paragraph(rowList.get(0).get(0).toString());
                document.add(p);
                PdfPTable table = new PdfPTable(9);
                table.setSpacingBefore(20);
                for (List<HSSFCell> row : rowList) {
                    for (HSSFCell hssfCell : row) {
                        // TODO aufhbschen und nicht toString() nutzen
                        String stringCellValue = hssfCell.toString();
                        table.addCell(stringCellValue);
                    }
                }
                document.add(table);
            }

            document.close();
            out.flush();
            facesContext.responseComplete();
        } catch (Exception e) {
            logger.error(e);
        }
    }
}

From source file:Excel.LeerExcel.java

/**
* This method is used to print the cell data to the console.
* @param cellDataList - List of the data's in the spreadsheet.
*///from   w w  w . j a v  a 2 s.  c  om
private void printToConsole(List cellDataList) {
    String error = "";
    int fila = 0;

    Boolean verif = false;
    ArrayList lstArt = new ArrayList();
    String unidadDeMedida = "";
    Double peso = 0.00;

    Integer porc = 0;
    String barra = null;
    String descripcion = null;
    String rubro = null;
    String talle1 = null;
    String talle2 = null;
    String talle3 = null;
    String talle4 = null;
    String talle5 = null;
    String talle6 = null;
    String talle7 = null;
    String talle8 = null;
    String talle9 = null;
    String precio = null;
    String talle = null;
    String sentencia = "insert into articulos (BARRAS,NOMBRE,SERVICIO,COSTO,PRECIO) value ";

    for (int i = 0; i < cellDataList.size(); i++) {
        List cellTempList = (List) cellDataList.get(i);

        int alerta = 0;

        for (int j = 0; j < cellTempList.size(); j++) {
            HSSFCell hssfCell = (HSSFCell) cellTempList.get(j);
            String stringCellValue = hssfCell.toString();
            //System.err.println("Contenido: "+j+" "+stringCellValue);
            //descripcion="";
            //if(i > 0){
            switch (j) {
            case 0:
                //numeroComprobante=stringCellValue;
                //descrip=String.valueOf(stringCellValue);

                //rubro=stringCellValue;
                int hallado = stringCellValue.indexOf("L");
                if (hallado > -1) {
                    rubro = stringCellValue;
                    alerta = 1;
                    System.out.println(j + " / RUBRO: " + rubro);
                } else {
                    porc = Numeros.ConvertirStringAInteger(stringCellValue);
                    barra = String.valueOf(porc);
                    alerta = 0;
                    System.out.println(j + " / BARRA: " + barra);
                }
                break;
            case 1:
                System.out.println(j + " / " + stringCellValue);
                //System.out.println("nombre: "+j+" "+stringCellValue);
                descripcion = stringCellValue;
                break;
            case 2:
                System.out.println(j + " / " + stringCellValue);
                //System.out.println("rfid: "+j+" "+stringCellValue);
                if (alerta == 1) {
                    porc = Numeros.ConvertirStringAInteger(stringCellValue);
                    talle1 = String.valueOf(porc);
                    //talle1=stringCellValue;

                } else {
                    precio = stringCellValue;
                    talle = talle1;
                }
                break;
            case 3:
                System.out.println(j + " / " + stringCellValue);
                //System.out.println("Direccion: "+j+" "+stringCellValue);
                if (alerta == 1) {
                    porc = Numeros.ConvertirStringAInteger(stringCellValue);
                    talle2 = String.valueOf(porc);
                    //talle2=stringCellValue;

                } else {
                    precio = stringCellValue;

                    talle = talle2;
                }
                break;
            case 4:
                System.out.println(j + " / " + stringCellValue);
                //System.out.println("Teelfono: "+j+" "+stringCellValue);
                if (alerta == 1) {
                    if (stringCellValue.equals("")) {

                    } else {
                        porc = Numeros.ConvertirStringAInteger(stringCellValue);
                        talle3 = String.valueOf(porc);
                    }
                    //talle3=stringCellValue;

                } else {
                    precio = stringCellValue;
                    talle = talle3;
                }
                break;
            case 5:
                System.out.println(j + " / " + stringCellValue);
                //System.out.println("Mail: "+j+" "+stringCellValue);
                if (alerta == 1) {
                    if (stringCellValue.equals("")) {

                    } else {
                        porc = Numeros.ConvertirStringAInteger(stringCellValue);
                        talle4 = String.valueOf(porc);
                    }
                    //talle4=stringCellValue;

                } else {
                    precio = stringCellValue;
                    talle = talle4;
                }

                break;
            case 6:
                System.out.println(j + " / " + stringCellValue);
                if (alerta == 1) {
                    if (stringCellValue.equals("")) {

                    } else {
                        porc = Numeros.ConvertirStringAInteger(stringCellValue);
                        talle5 = String.valueOf(porc);
                        //talle5=stringCellValue;
                    }

                } else {
                    precio = stringCellValue;
                    talle = talle5;
                }
                //fila++;
                break;
            case 7:
                System.out.println(j + " / " + stringCellValue);
                //tra.guardarRegistro(sql);
                if (alerta == 1) {
                    if (stringCellValue.equals("")) {

                    } else {
                        porc = Numeros.ConvertirStringAInteger(stringCellValue);
                        talle6 = String.valueOf(porc);
                    }
                    //talle6=stringCellValue;

                } else {
                    precio = stringCellValue;
                    talle = talle6;
                }
                break;
            case 8:
                System.out.println(j + " / " + stringCellValue);
                //fila++;
                if (alerta == 1) {
                    if (stringCellValue.equals("")) {

                    } else {
                        porc = Numeros.ConvertirStringAInteger(stringCellValue);
                        talle7 = String.valueOf(porc);
                    }
                    //talle7=stringCellValue;

                } else {
                    precio = stringCellValue;
                    talle = talle7;
                }
                break;
            case 9:
                System.out.println(j + " / " + stringCellValue);
                //fila++;
                if (alerta == 1) {
                    if (stringCellValue.equals("")) {

                    } else {
                        porc = Numeros.ConvertirStringAInteger(stringCellValue);
                        talle8 = String.valueOf(porc);
                    }
                    //talle8=stringCellValue;

                } else {
                    precio = stringCellValue;
                    talle = talle8;
                }
                break;
            case 10:
                System.out.println(j + " / " + stringCellValue);
                //fila++;
                if (alerta == 1) {
                    if (stringCellValue.equals("")) {

                    } else {
                        porc = Numeros.ConvertirStringAInteger(stringCellValue);
                        talle9 = String.valueOf(porc);
                    }
                    //talle9=stringCellValue;

                } else {
                    precio = stringCellValue;
                    talle = talle9;
                }

                break;

            }
            if (j > 1) {
                if (alerta == 0) {
                    System.out.println(precio);
                    if (precio.equals("")) {
                    } else {
                        sentencia += "('" + rubro + barra + talle + "','" + descripcion + " Talle:" + talle
                                + "',0,0," + precio + "),";
                        precio = null;
                    }

                }
            }
            //System.out.println("CODIGO: "+rubro+barra+talle+" $ "+precio);

            //}
            //System.err.println("FINAL");

            //fac.modificar(cliente);

        }

        System.out.println("  FINAL DE RENGLON");
        barra = null;
        fila++;
    }
    System.err.println(sentencia);
    JOptionPane.showMessageDialog(null, "PROCESO EXITOSO \n CANTIDAD DE FILAS PROCESADAS " + fila);
}

From source file:fr.ens.transcriptome.aozan.io.CasavaDesignXLSReader.java

License:Open Source License

/**
 * Parse the content of a cell./*w w w . j av  a 2 s  .co  m*/
 * @param cell cell to parse
 * @return a String with the cell content
 */
private static String parseCell(final HSSFCell cell) {

    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        final double doubleValue = cell.getNumericCellValue();

        if (DoubleMath.isMathematicalInteger(doubleValue)) {
            return Long.toString((long) doubleValue);
        }
    }

    return cell.toString();
}

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

License:Open Source License

public void fillData() {
    try {/*from ww  w .  ja va 2s  . c om*/
        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(i);
                this.head.add(cell.toString());
            }
            this.readMetabolites(initRow + 1, numberRows, sheet);

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

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

License:Open Source License

/**
 * Reads lipid information of one row./*from   w w  w.  j  a  va2s. c om*/
 * @param row
 * @param numberCols
 * @return
 */
public void readRow(HSSFRow row) {
    HSSFCell cell;
    SimplePeakListRowGCGC metabolite = new SimplePeakListRowGCGC();
    for (int i = 0; i < row.getLastCellNum(); i++) {
        try {
            String title = head.get(i);
            if (title == null) {
                continue;
            }
            cell = row.getCell(i);
            boolean isfound = false;

            for (GCGCColumnName field : GCGCColumnName.values()) {
                if (title.matches(field.getRegularExpression())) {
                    metabolite.setVar(field.getSetFunctionName(),
                            this.getType(cell.toString(), field.getType()));
                    isfound = true;
                    break;
                }
            }

            if (!isfound) {
                try {
                    metabolite.setPeak(title, cell.getNumericCellValue());
                } catch (Exception e) {
                    metabolite.setPeak(title, 0.0);
                }
            }

            if (metabolite.getName() == null) {
                metabolite.setName("unknown");
            }
        } catch (Exception exception) {
            //exception.printStackTrace();
        }
    }
    this.dataset.addRow(metabolite);
}

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

License:Open Source License

/**
 *
 * @param sheet/*  w  ww  . ja v a2s.  c  o m*/
 * @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(0);

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

    return num;
}