private static List<String> readExcelFile() { List<String> datas = new ArrayList<>(); try (FileInputStream inputStream = new FileInputStream("/sdcard/Template/IC1001.xlsx"); Workbook workbook = WorkbookFactory.create(inputStream)) { // 获取第一个 Sheet Sheet sheet = workbook.getSheetAt(4); // 遍历 Sheet 中的每一行和每一列 Iterator<Row> rowIterator = sheet.rowIterator(); while (rowIterator.hasNext()) { ImportViewModel importViewModel = new ImportViewModel(); Row row = rowIterator.next(); while (rowIterator.hasNext()) { for (int i = 0; i < datas.size(); i+=4) { importViewModel.setName("商品名称:" + row.getCell(i).getStringCellValue()); importViewModel.setType("商品名称:" + row.getCell(i+1).getStringCellValue()); importViewModel.setStyle("商品名称:" + row.getCell(i+2).getStringCellValue()); importViewModel.setInventoryNum("预期应有库存:" + row.getCell(i+3).getStringCellValue()); } } workbook.close(); inputStream.close(); } } catch (IOException | InvalidFormatException e) { e.printStackTrace(); } return datas; }有什么问题,怎么修改
时间: 2023-08-03 09:06:52 浏览: 79
这段代码有以下几个问题:
1. 在 while 循环外部关闭 Workbook 和 FileInputStream,应该在 finally 中关闭,以确保资源能够被正确释放。
2. 在第二个 while 循环中,应该使用 columnIterator 来遍历每一列,而不是使用一个 for 循环来遍历 datas 列表。
3. 在设置 ImportViewModel 的属性时,属性名写错了,应该是 name、type、style、inventoryNum,而不是多次写商品名称。
下面是修改后的代码:
```
private static List<ImportViewModel> readExcelFile() {
List<ImportViewModel> datas = new ArrayList<>();
FileInputStream inputStream = null;
Workbook workbook = null;
try {
inputStream = new FileInputStream("/sdcard/Template/IC1001.xlsx");
workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(4);
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
ImportViewModel importViewModel = new ImportViewModel();
Iterator<Cell> columnIterator = row.cellIterator();
while (columnIterator.hasNext()) {
importViewModel.setName("商品名称:" + columnIterator.next().getStringCellValue());
importViewModel.setType("商品类型:" + columnIterator.next().getStringCellValue());
importViewModel.setStyle("商品款式:" + columnIterator.next().getStringCellValue());
importViewModel.setInventoryNum("预期应有库存:" + columnIterator.next().getStringCellValue());
datas.add(importViewModel);
}
}
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
} finally {
try {
if (workbook != null) {
workbook.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return datas;
}
```
阅读全文