使用Apache POI在与复杂公式关联的Excel文件中获取最后填充的行号

时间:2016-03-08 10:17:26

标签: java excel apache-poi

复杂公式应用于列直到excel表的末尾。但是当我使用Sheet.getLastRowNum()检索最后一个行号时 虽然excel表只有10行,但它正在返回工作表的最后一行。即使是excel文件中的任何方式也可以获得确切的最后一行 应用于excel表末尾的公式?

1 个答案:

答案 0 :(得分:0)

来自http://affy.blogspot.cz/2004/04/poi-optimization-eliminating-trailing.html
检索所需的公式然后使用此代码。它将删除所有这些空行,然后您可以使用数据检索代码获取所需数据。

List yourlist = new ArrayList();
        String value = null;
        FileInputStream inputStreams1 = null;
        inputStreams1 = new FileInputStream(FileNameWithPath);
        org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(inputStreams1);
        HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(0);
        Iterator<Row> iterator = sheet.iterator();

        boolean stop = false;
        boolean nonBlankRowFound;
        short c;
        HSSFRow lastRow = null;
        HSSFCell cell = null;
        HSSFRow FirsttRow = null;

        while (stop == false) {
            nonBlankRowFound = false;
            lastRow = (HSSFRow) sheet.getRow(sheet.getLastRowNum());
            for (c = lastRow.getFirstCellNum(); c <= lastRow.getLastCellNum(); c++) {
                cell = lastRow.getCell(c);
                if (cell != null && lastRow.getCell(c).getCellType() != HSSFCell.CELL_TYPE_BLANK) {
                    nonBlankRowFound = true;
                }
            }
            if (nonBlankRowFound == true) {
                stop = true;

                yourlist =  yourMethod(FileNameWithPath, sheet); //updated HSSFSheet object which will have 10 rows
                /*use this code to remove all those empty rows then use hsheet object. now use this hsheet object will
                 have only non empty rows(in your case 10 rows)*/

            } else {
                sheet.removeRow(lastRow);


            }
        }