poi 读取 excel 总行数 ,总列数 注意事项 lastRowNum 、lastCellNum
https://blog.csdn.net/HaHa_Sir/article/details/127235280
poi 读取 excel 总行数 ,总列数 注意事项 lastRowNum 、lastCellNum
一、概述
1、如下图,有一个 4行 3列的excel 表格数据,用 poi 读取后,分别获取 最大行号 和 列号, 预期是的: 行数为4,列数为3 ; 而实际却是: 行数 和 列数都是 3 .
二、大概代码
1、读取excel 文件代码
- public static void main(String[] args) throws IOException, InvalidFormatException {
- String path ="/excel模板-内容修改.xlsx";
- InputStream in = ExcelCellUpdateTest.load(path);
- Workbook workbook = WorkbookFactory.create(in);
- Sheet sheet = workbook.getSheetAt(0);
- for (Row row : sheet) {
-
- }
- int firstRowNum = sheet.getFirstRowNum();
- int lastRowNum = sheet.getLastRowNum();
- System.out.println("firstRowNum =" + firstRowNum + " \t lastRowNum="+lastRowNum);
-
- Row row0 = sheet.getRow(0);
- int rowNum = row0.getRowNum();
- System.out.println("rowNum = "+ rowNum);
-
- short lastCellNum = row0.getLastCellNum();
- short firstCellNum = row0.getFirstCellNum();
- int physicalNumberOfCells = row0.getPhysicalNumberOfCells();
- System.out.println("firstCellNum= "+firstCellNum + "\t lastCellNum = "+ lastCellNum + " \t physicalNumberOfCells="+physicalNumberOfCells);
-
- for (int i = 0; i <= lastRowNum; i++) {
- Row row = sheet.getRow(i);
- for (int j = 0; j < lastCellNum; j++) {
- Cell cell = row.getCell(j);
- String s = null ;
- if(Objects.nonNull(cell)){
- s = cell.toString();
- }
- System.out.print("cell num :"+ j + " cell val :"+ s +" \t");
- }
- System.out.println();
- }
- }
1.1、输出结果:
- firstRowNum =0 lastRowNum=3
- rowNum = 0
- firstCellNum= 0 lastCellNum = 3 physicalNumberOfCells=3
- cell num :0 cell val :姓名 cell num :1 cell val :年龄 cell num :2 cell val :addr
- cell num :0 cell val :小明 cell num :1 cell val :18.0 cell num :2 cell val :北京市
- cell num :0 cell val :小红 cell num :1 cell val :22.0 cell num :2 cell val :中国
- cell num :0 cell val :小刚 cell num :1 cell val :33.0 cell num :2 cell val :朝阳区
三、总结
1、poi 读取excel文件中, 起始 行号 和 列号,都是 0 开始 ( firstRowNum =0 / firstCellNum= 0); 总行号计数: 从 0 开始计数,总行数应该为: lastRowNum+1 ,实际显示的结果是:总行数-1 ,在循环读取行数的时候,应该注意:
- for (int i = 0; i <= lastRowNum; i++) {
- // 应该是: <= 等于
- }
或者:
- for (int i = 0; i < lastRowNum+1 ; i++) {
- // 应该是: lastRowNum+1
- }
否则不能读取全部的行数!
2、总列号计数:从1开始计数,总列数 = lastCellNum ; 和实际总列数是一致的,无需特别处理。 因 起始 行号 和 列号,都是 0 开始 ,所以读取列数的时候,常规读取即可,如下:
- for (int j = 0; j < lastCellNum; j++) {
-
- }
更多是poi excel 相关知识:
1、 https://thinkcode.blog.csdn.net/article/details/105232822
2、https://thinkcode.blog.csdn.net/article/details/126602426
标签:总列数,读取,val,lastCellNum,cell,num,lastRowNum From: https://www.cnblogs.com/sunny3158/p/17481184.html