How to read alphanumeric values from Excel cells in Java?

[亡魂溺海] 提交于 2021-02-11 16:01:02

问题


I have to read a ZIP code from Excel sheet. Zip code can be any of the following formats:

ααααα
11111-αααα
3  3  3  3  3 - 6  6  6  6
12345 123456
12345-123456

I tried cell.getRichStringCellValue() and cell.getStringCellValue()but it's not working.


回答1:


enter image description here

Above is the Image of the excel. I have used poi to get the data, looks like you have used poi but not 100% sure. Below is the code that is working and reading all the values

public static void main(String[] args) throws IOException {
        FileInputStream file = new FileInputStream(new File("zip.xls"));

        //Get the workbook instance for XLS file 
        HSSFWorkbook workbook = new HSSFWorkbook(file);
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
        //Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheetAt(0);

        //Get iterator to all the rows in current sheet
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext())
        {
            Row row = rowIterator.next();
            //For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext())
            {
                Cell cell = cellIterator.next();
                //Check the cell type after eveluating formulae
                //If it is formula cell, it will be evaluated otherwise no change will happen
                switch (evaluator.evaluateInCell(cell).getCellType())
                {
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t\t");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t\t");
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        //System.out.print(cell.getStringCellValue() + "\t\t");
                        break;
                }
            }
            System.out.println("");
        }
        file.close();
    }


来源:https://stackoverflow.com/questions/20884318/how-to-read-alphanumeric-values-from-excel-cells-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!