从java读取xlsRead

时间:2014-04-09 14:10:44

标签: java excel file

需要帮助,

我有一个Excel文件

TN  FN      MN  LN      Type
MR  Test1   t1  Test1   abc
MR  Test2   t2          abc
MR          t3  Test3   abc
MR  Test4   t4  Test4   abc

我的要求是:

  1. 从java程序中读取行
  2. 检查无效行(如果第2列或第4列为空/空,那么它将是无效行并将此行存储在list1中)
  3. 检查有效行(如果第2列或第4列都不为空/空,则它将是有效行并将此行存储在list2中)
  4. 1)

    FileInputStream file = new FileInputStream("c:\\test.xls");
    
    //Get the workbook instance for XLS file 
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    
    //Get first sheet from the workbook
    XSSFSheet sheet = workbook.getSheetAt(0);
    
    //Iterate through each rows from first sheet
    Iterator<Row> rowIterator = sheet.iterator();
    while(rowIterator.hasNext()) {
        Row row = rowIterator.next();
    
        //For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        while(cellIterator.hasNext()) {
    
            Cell cell = cellIterator.next();
    
            switch(cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.print(cell.getBooleanCellValue() + "\t\t");
                    break;
                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;
            }
    
        }
        System.out.println("");
    }
    file.close();
    FileOutputStream out = 
        new FileOutputStream(new File("C:\\Users\\IBM_ADMIN\\Desktop\\test.xls"));
    workbook.write(out);
    out.close();
    
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    
    }
    

    2)我被困在这里,我怎样才能获得有效和无效的行?

    感谢您的帮助

1 个答案:

答案 0 :(得分:0)

POI需要一点点习惯。您必须明确检查单元格是空白还是空。

SO上有一个很好的例子here