private List<String> readExcelFile() { List<String> datas = new ArrayList<>(); File sdDir; try { // 获取 Excel 文件路径 sdDir = new File("/sdcard/Template/", "IC1001.xlsx"); // 创建 Workbook 对象 FileInputStream inputStream = new FileInputStream(sdDir); Workbook workbook = WorkbookFactory.create(inputStream); // 获取第一个 Sheet Sheet sheet = workbook.getSheetAt(0); // 遍历 Sheet 中的每一行和每一列 Iterator<Row> rowIterator = sheet.rowIterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); datas.add(cell.toString()); } // 关闭 Workbook 和输入流 workbook.close(); inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } catch (InvalidFormatException e) { throw new RuntimeException(e); } return datas; }有什么问题
时间: 2023-07-16 17:14:31 浏览: 111
dinov2代码与预训练模型
这段代码的问题在于,当有多行数据时,只会读取第一行数据,因为关闭Workbook和输入流的代码应该在循环结束后执行,而不是在每个行的末尾执行。应该将这两行代码移出while循环,放在try块的末尾。另外,如果发生异常,也应该关闭Workbook和输入流。例如:
```
private List<String> readExcelFile() {
List<String> datas = new ArrayList<>();
File sdDir;
FileInputStream inputStream = null;
Workbook workbook = null;
try {
// 获取 Excel 文件路径
sdDir = new File("/sdcard/Template/", "IC1001.xlsx");
// 创建 Workbook 对象
inputStream = new FileInputStream(sdDir);
workbook = WorkbookFactory.create(inputStream);
// 获取第一个 Sheet
Sheet sheet = workbook.getSheetAt(0);
// 遍历 Sheet 中的每一行和每一列
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
datas.add(cell.toString());
}
}
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (workbook != null) {
workbook.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return datas;
}
```
阅读全文