简体   繁体   English

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

[英]Get exact last filled row number in an excel file that has is associated with a complex formula using Apache POI

一个复杂的公式会应用于一列直到Excel表格的末尾。但是当我使用Sheet.getLastRowNum()检索最后一行时,尽管excel表格只有10行,但它返回的是表格的最后一行。即使公式应用于Excel工作表的末尾,有什么方法可以在Excel文件中获得确切的最后填充行?

From http://affy.blogspot.cz/2004/04/poi-optimization-eliminating-trailing.html 来自http://affy.blogspot.cz/2004/04/poi-optimization-eliminate-trailing.html
Retrieve required formula then use this code. 检索所需的公式,然后使用此代码。 it will remove all those empty rows and then you can get required data with your data retrieving code. 它将删除所有这些空行,然后您可以使用数据检索代码获得所需的数据。

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


            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM