springmvc通过excel进行数据导入
时间: 2023-09-02 14:14:06 浏览: 85
SpringMVC 可以通过 Apache POI 库来读取 Excel 文件,并将数据导入到数据库中。具体步骤如下:
1. 引入 Apache POI 库:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
```
2. 编写 Controller 代码,包括上传 Excel 文件、读取 Excel 文件、将数据导入到数据库中:
```java
@Controller
public class ExcelController {
@PostMapping("/upload")
public String uploadExcel(@RequestParam("file") MultipartFile file) throws Exception {
// 读取 Excel 文件
FileInputStream fis = new FileInputStream(file.getFile());
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
// 遍历 Excel 数据,并将其存入数据库中
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
String name = row.getCell(0).getStringCellValue();
int age = (int) row.getCell(1).getNumericCellValue();
// 将数据存入数据库中
}
// 关闭资源
workbook.close();
fis.close();
return "success";
}
}
```
3. 编写上传页面,包括上传按钮和文件选择框:
```html
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">上传</button>
</form>
```
以上就是使用 SpringMVC 实现 Excel 数据导入的基本步骤。