Excel 数据导入数据库:使用 Spring Boot + Thymeleaf + JPA 实现
将 Excel 表格中的数据存储到数据库表中,前端使用 Thymeleaf,后端使用 Spring Boot + JPA
本教程将演示如何使用 Spring Boot、Thymeleaf 和 JPA 将 Excel 表格中的数据导入到数据库表中。
1. 前端页面
在前端页面中,添加一个文件上传的 input 标签和一个提交按钮:
<form method='post' enctype='multipart/form-data' th:action='@{/upload}'>
<input type='file' name='file' />
<input type='submit' value='上传' />
</form>
2. 后端 Controller
在后端 Controller 中,接收上传文件并处理:
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
// 读取上传文件
Workbook workbook;
if (file.getOriginalFilename().endsWith(".xls")) {
workbook = new HSSFWorkbook(file.getInputStream());
} else {
workbook = new XSSFWorkbook(file.getInputStream());
}
// 遍历 Excel 表格,将数据存入数据库
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rows = sheet.iterator();
while (rows.hasNext()) {
Row row = rows.next();
// 读取每一行的数据
String name = row.getCell(0).getStringCellValue();
int age = (int) row.getCell(1).getNumericCellValue();
String gender = row.getCell(2).getStringCellValue();
// 将数据存入数据库
User user = new User(name, age, gender);
userRepository.save(user);
}
return "redirect:/";
}
3. 后端 User 实体类
在后端定义 User 实体类,并使用 JPA 操作数据库:
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
private String gender;
// 构造函数、getter、setter 省略
}
public interface UserRepository extends JpaRepository<User, Long> {
}
4. 前端展示表格
在前端页面中,添加一个展示数据库中数据的表格:
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr th:each='user : ${users}'>
<td th:text='${user.name}'></td>
<td th:text='${user.age}'></td>
<td th:text='${user.gender}'></td>
</tr>
</tbody>
</table>
5. 后端查询数据
在后端 Controller 中,查询数据库中的数据并返回给前端页面:
@GetMapping("/")
public String getUsers(Model model) {
List<User> users = userRepository.findAll();
model.addAttribute("users", users);
return "index";
}
代码示例
完整的代码示例请参考以下链接:
总结
本教程演示了如何使用 Spring Boot、Thymeleaf 和 JPA 将 Excel 表格中的数据导入到数据库表中,并展示了如何将数据从数据库查询并展示在前端页面上。
希望本教程能够帮助您快速掌握使用 Spring Boot 和 JPA 操作数据库的基本操作。
原文地址: https://www.cveoy.top/t/topic/oacl 著作权归作者所有。请勿转载和采集!