java 利用POI 读取Excel数据的真实有效行数 | 您所在的位置:网站首页 › 为什么excel没有行数 › java 利用POI 读取Excel数据的真实有效行数 |
前言
最近发现java导入excel数据时,我的excel数据明明只有4条数据,可是java程序却读取到了第6行。检查代码发现5、6行不小心设置了行高,导致poi的getLastRowNum()方法读取到了5、6行数据。真坑啊,我想要的是有真实数据的行数。于是,我换了中方式来获取excel的数据行数(校验excel是否存在数据),今天把我修改的代码记录下来分享给大家~~ 准备工作 1、准备测试数据(第5.6行只设置了行高,没有赋值):![]() 获取excel的最后一行数据: package com.cll.test; import com.cll.DemoApplication; import org.apache.poi.ss.util.CellReference; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.apache.poi.ss.usermodel.*; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import static org.apache.poi.ss.usermodel.CellType.*; /** * Created by Administrator on 2021/07/05. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = DemoApplication.class) public class Mytestinfo { @Test public void importExcel() { try { String filename = "C://Users/Administrator/Desktop/提取结果1.xlsx"; InputStream inputStream = new FileInputStream(filename); Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); //获取sheet的行数 int rows = sheet.getLastRowNum() + 1; System.out.println("使用poi自带的getLastRowNum方法获取的行数为:" + rows); CellReference cellReference = new CellReference("A4"); boolean flag = false; for (int i = cellReference.getRow(); i sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1); continue; } flag = false; for (Cell c : r) { if (c.getCellType() == STRING || c.getCellType() == NUMERIC || c.getCellType() == BOOLEAN || c.getCellType() == FORMULA || c.getCellType() == ERROR) { flag = true; break; } } if (flag) { i++; continue; } else {//如果是空白行(即可能没有数据,但是有一定格式) if (i == sheet.getLastRowNum()) {//如果到了最后一行,直接将那一行remove掉 sheet.removeRow(r); } else {//如果还没到最后一行,则数据往上移一行 sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1); } //写入excel FileOutputStream os = new FileOutputStream(filename); workbook.write(os); } } System.out.println("校验空值后得到的行数为:" + (sheet.getLastRowNum() + 1)); } catch (Exception e) { System.out.println("获取异常信息:"+e.getMessage()); } } } 运行结果
|
CopyRight 2018-2019 实验室设备网 版权所有 |