Spring Boot + Thymeleaf + Apache POI 实现 Excel 文件上传并解析存储到数组
本文将介绍如何使用 Spring Boot、Thymeleaf 和 Apache POI 库实现前端上传 Excel 文件,后端解析文件内容并将数据存储到数组,并通过 Thymeleaf 模板展示解析结果。
前端代码
<form action="#" th:action="@{/upload}" method="post" enctype="multipart/form-data"><input type="file" name="file" id="file"><button type="submit">上传</button><button type="button" onclick="cancel()">取消</button></form>
后端代码
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file, Model model) throws IOException {
List<String[]> dataList = new ArrayList<>();
// 读取 Excel 文件
Workbook workbook = WorkbookFactory.create(file.getInputStream());
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
String[] rowData = new String[row.getLastCellNum()];
for (Cell cell : row) {
String cellValue = "";
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
default:
break;
}
rowData[cell.getColumnIndex()] = cellValue;
}
dataList.add(rowData);
}
model.addAttribute("dataList", dataList);
return "result";
}
其中,上传的 Excel 文件会被保存为 MultipartFile 类型的对象,可以通过 getInputStream() 方法获取输入流,然后使用 Apache POI 库读取 Excel 文件。读取后的数据存储在一个 List<String[]> 中,每个 String[] 表示一行数据,其中的每个元素表示该行中的一个单元格的值。最后将数据传递给 Thymeleaf 模板,进行展示。
原文地址: https://www.cveoy.top/t/topic/oeL0 著作权归作者所有。请勿转载和采集!