编写使用SpringBoot读取Excel文件的代码
时间: 2024-05-04 07:15:52 浏览: 137
可以使用Apache POI来读取Excel文件,以下是使用SpringBoot和Apache POI的代码示例:
```
@Autowired
private ResourceLoader resourceLoader;
@GetMapping("/readExcel")
public List<MyData> readExcel() throws IOException {
List<MyData> dataList = new ArrayList<>();
Resource resource = resourceLoader.getResource("classpath:mydata.xlsx");
try (InputStream inputStream = resource.getInputStream()) {
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
MyData data = new MyData();
while (cellIterator.hasNext()) {
Cell nextCell = cellIterator.next();
int columnIndex = nextCell.getColumnIndex();
switch (columnIndex) {
case 0:
data.setId((long) nextCell.getNumericCellValue());
break;
case 1:
data.setName(nextCell.getStringCellValue());
break;
case 2:
data.setAge((int) nextCell.getNumericCellValue());
break;
}
}
dataList.add(data);
}
workbook.close();
}
return dataList;
}
```
这个代码将读取位于 classpath 中的名为 mydata.xlsx 的 Excel 文件,并返回一个包含 MyData 对象的列表。详细的解释可以参考注释。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)