springboot后端导入导出excel接口
时间: 2023-10-09 11:07:08 浏览: 123
实导入导出Excel功能可以使用Apache POI库,这里提供一个基于Spring Boot的简单示例代码。
1.添加依赖
在pom.xml文件中添加以下依赖:
```xml
<!--excel导入导出-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
2.实现导出Excel接口
```java
@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
// 创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建工作表
XSSFSheet sheet = workbook.createSheet("Sheet1");
// 设置表头
String[] headers = {"姓名", "年龄", "性别"};
XSSFRow headerRow = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
XSSFCell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
}
// 填充数据
List<User> userList = userService.getAll();
for (int i = 0; i < userList.size(); i++) {
User user = userList.get(i);
XSSFRow row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(user.getName());
row.createCell(1).setCellValue(user.getAge());
row.createCell(2).setCellValue(user.getGender());
}
// 输出Excel文件
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=user.xlsx");
workbook.write(response.getOutputStream());
workbook.close();
}
```
3.实现导入Excel接口
```java
@PostMapping("/import")
public void importExcel(@RequestParam("file") MultipartFile file) throws IOException {
// 读取Excel文件
XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
XSSFSheet sheet = workbook.getSheetAt(0);
// 解析数据
List<User> userList = new ArrayList<>();
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
XSSFRow row = sheet.getRow(i);
User user = new User();
user.setName(row.getCell(0).getStringCellValue());
user.setAge((int) row.getCell(1).getNumericCellValue());
user.setGender(row.getCell(2).getStringCellValue());
userList.add(user);
}
// 批量插入数据库
userService.batchInsert(userList);
workbook.close();
}
```
以上代码仅供参考,具体实现可根据自己的业务需求进行修改。
阅读全文