poi操作Excel 被bug坑了getLastRowNum,getPhysicalNumberOfRows,getPhysicalNumberOfCells,getLastCellNum


getLastRowNum  

    如果sheet中一行數據都沒有則返回-1,只有第一行有數據則返回0,最后有數據的行是第n行則返回 n-1;

getLastCellNum   

    如果row中一列數據都沒有則返回-1,只有第一列有數據則返回1,最后有數據的列是第n列則返回 n;

 

getPhysicalNumberOfRows  

    獲取有記錄的行數,即:最后有數據的行是第n行,前面有m行是空行沒數據,則返回n-m;

getPhysicalNumberOfCells   

    獲取有記錄的列數,即:最后有數據的列是第n列,前面有m列是空列沒數據,則返回n-m;

 

奇怪的是 getLastRowNum 和 getLastCellNum 的邏輯不一致,根據方法命名的話,應該是返回最后一行的行數或者最后一列的列數。

如果沒有行或列應該返回0,而不應該返回-1。

而且 getLastRowNum 返回的是最后一行的索引而不是最后一行的行數,getLastCellNum則是返回的最后一列的列數。

 

文件數據:

 

 

代碼演示:

package com.liyh;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @Author: liyh
 * @Date: 2020/10/26 17:24
 */
public class Test {

    @org.junit.jupiter.api.Test
    public void test() throws UnsupportedEncodingException {
        File file = new File("C:/Maiun/rizhi/項目清單.xlsx");
        String filePath = URLDecoder.decode(file.getPath(), "utf-8");
        File xlsfile = new File(filePath);
        try (FileInputStream is = new FileInputStream(xlsfile)) {
            //同時支持Excel 2003、2007
            Workbook workbook = WorkbookFactory.create(is); //這種方式 Excel 2003/2007/2010 都是可以處理的
            Sheet sheet = workbook.getSheetAt(0);
            System.out.println("getLastRowNum: " + sheet.getLastRowNum());
            System.out.println("getPhysicalNumberOfRows: " + sheet.getPhysicalNumberOfRows());
            int rowCount = sheet.getLastRowNum() + 1; //獲取總行數
            for (int i = 0; i < rowCount; i++) {
                Row row = sheet.getRow(i);
                int cellCount = 0;
                if (row != null) {//row  該行所有單元格為空時,row是null值    2017-01-05 pelin
                    cellCount = row.getLastCellNum();//獲取最后一個不為空的列是第幾個。
                    System.out.println(i + "索引行getLastCellNum: " + cellCount);
                    System.out.println(i + "索引行getPhysicalNumberOfCells: " + row.getPhysicalNumberOfCells());

                    cellCount = cellCount < 0 ? 0 : cellCount;//getLastCellNum沒有單元格時會返回負數
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

測試結果:文件的數據是5行,共7列。

  

 

  

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM