比如现在有一个这样的excel文件:
现在就要实现把这些数据读取出来。
1、首先导入apache的依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<!-- 读取大量excel数据时使用 -->
<dependency>
<groupId>com.monitorjbl</groupId>
<artifactId>xlsx-streamer</artifactId>
<version>2.1.0</version>
</dependency>
2、代码实现:
public static List<List<String>> readMtExcel(FileInputStream in) throws Exception{
Workbook wk = StreamingReader.builder()
.rowCacheSize(100) //缓存到内存中的行数,默认是10
.bufferSize(4096) //读取资源时,缓存到内存的字节大小,默认是1024
.open(in); //打开资源,必须,可以是InputStream或者是File,注意:只能打开XLSX格式的文件
//读取excel第一个工作簿
Sheet sheet = wk.getSheetAt(0);
//存放所有数据的集合
List<List<String>> lists = new ArrayList<>();
//遍历所有的行
for (Row row : sheet) {
System.out.println("开始遍历第" + row.getRowNum() + "行数据:");
if (row.getRowNum() == 370) //只有370条数据,遍历到370行就跳出循环
break;
//存放每一行数据的集合
List<String> rowList = new ArrayList<>();
//遍历每一行数据
//StringBuffer sb = new StringBuffer();
for (Cell cell : row) {
System.out.print(cell.getStringCellValue() + "--");
//把每个单元格的数据一一放进每一行集合中
rowList.add(cell.getStringCellValue());
}
//把每行数据一行一行放进整个集合中
lists.add(rowList);
}
return lists;
}
注意:当你的excel文件很大的时候,不导入这个依赖就会报错!!!会报内存溢出!!!
<dependency>
<groupId>com.monitorjbl</groupId>
<artifactId>xlsx-streamer</artifactId>
<version>2.1.0</version>
</dependency>
3、测试结果:
@Test
public void test2() throws Exception {
FileInputStream in = new FileInputStream("C:\\Users\\xiaozhu\\Desktop\\美团批量新增标品.xlsx");
ExcelUtils.readMtExcel(in);
}