当解析的excel文件过大时,可能会造成占用内存过大, 此方法只针对 xlsx格式的excel。
1 工程中引入jar包
<dependency>
<groupId>com.monitorjbl</groupId>
<artifactId>xlsx-streamer</artifactId>
<version>2.2.0</version>
</dependency>
2 读取方式1
private static void readBigExcel(String filePath) throws FileNotFoundException {
FileInputStream in = new FileInputStream(filePath);
StreamingReader reader = StreamingReader.builder()
.rowCacheSize(100)
.bufferSize(4096)
.sheetIndex(0)
.read(in);
for (Row r : reader) {
for (Cell c : r) {
System.out.print(c.getStringCellValue() + " ");
}
System.out.println();
}
}
3 读取方式2
public static List<Map<Integer, String>> getStreamWorkbook(String filePath) throws FileNotFoundException {
FileInputStream in = new FileInputStream(filePath);
Workbook wk = StreamingReader.builder()
.rowCacheSize(100)
.bufferSize(4096)
.open(in);
Sheet sheet = wk.getSheetAt(0);
List<Map<Integer, String>> list = new ArrayList<>();
for (Row row : sheet) {
if (isTitle) {
isTitle = false;
continue;
}
System.out.println("开始遍历第" + row.getRowNum() + "行数据:");
Map<Integer, String> map = new HashMap<>();
Set<Map.Entry<Integer, Cell>> entries = ((StreamingRow)row).getCellMap().entrySet(); Iterator<Map.Entry<Integer, Cell>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Cell> next = iterator.next();
Integer key = next.getKey();
String value = next.getValue().getStringCellValue();
map.put(key, value);
}
list.add(map);
}
return list;
好好学习天天向上
原文链接:blog.csdn.net/weixin_3764…