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(0); Iterator<Row> rowIterator = sheet.rowIterator(); if (rowIterator.hasNext()) { rowIterator.next(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> columnIterator = row.cellIterator(); ImportViewModel importViewModel = new ImportViewModel(); Cell cell = columnIterator.next(); importViewModel.setName("商品名称:" + String.valueOf(cell.getNumericCellValue())); cell = columnIterator.next(); importViewModel.setType("商品类型:" + cell.getStringCellValue()); cell = columnIterator.next(); importViewModel.setStyle("商品款式:" +cell.getStringCellValue()); cell = columnIterator.next(); importViewModel.setInventoryNum("预期应有库存:" + cell.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; }怎么样才能接受excel表格中任意类型的数据
时间: 2023-12-10 11:40:54 浏览: 143
jsp页面iterator遍历数组、Map、List
你可以使用`org.apache.poi.ss.usermodel.DataFormatter`类将单元格中的数据转换为字符串,这样就可以接受任意类型的数据了。以下是修改后的代码:
```
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(0);
Iterator<Row> rowIterator = sheet.rowIterator();
if (rowIterator.hasNext()) {
rowIterator.next();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> columnIterator = row.cellIterator();
ImportViewModel importViewModel = new ImportViewModel();
Cell cell = columnIterator.next();
importViewModel.setName("商品名称:" + new DataFormatter().formatCellValue(cell));
cell = columnIterator.next();
importViewModel.setType("商品类型:" + new DataFormatter().formatCellValue(cell));
cell = columnIterator.next();
importViewModel.setStyle("商品款式:" + new DataFormatter().formatCellValue(cell));
cell = columnIterator.next();
importViewModel.setInventoryNum("预期应有库存:" + new DataFormatter().formatCellValue(cell));
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;
}
```
阅读全文