如何从Java中的Excel单元格中读取字母数字值?

时间:2014-01-02 13:41:55

标签: java file file-io

我必须从Excel表格中读取邮政编码。邮政编码可以是以下任何格式:

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

我尝试了cell.getRichStringCellValue()cell.getStringCellValue(),但它无效。

1 个答案:

答案 0 :(得分:1)

enter image description here

以上是excel的形象。我用poi来获取数据,看起来你已经使用过poi但不是100%肯定。下面是正在运行并读取所有值的代码

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();
    }