springboot excel导入导出具体代码
时间: 2023-04-01 14:03:09 浏览: 114
你好,以下是 Spring Boot 实现 Excel 导入导出的示例代码:
1. 导入 Excel
```
@PostMapping("/import")
public String importExcel(@RequestParam("file") MultipartFile file) throws IOException {
// 读取 Excel 文件
Workbook workbook = WorkbookFactory.create(file.getInputStream());
Sheet sheet = workbook.getSheetAt();
// 遍历行
for (Row row : sheet) {
// 遍历单元格
for (Cell cell : row) {
// 处理单元格数据
String value = cell.getStringCellValue();
// ...
}
}
return "导入成功";
}
```
2. 导出 Excel
```
@GetMapping("/export")
public void exportExcel(HttpServletResponse response) throws IOException {
// 创建 Excel 文件
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// 写入数据
Row row = sheet.createRow();
Cell cell = row.createCell();
cell.setCellValue("Hello, World!");
// 输出 Excel 文件
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=test.xlsx");
workbook.write(response.getOutputStream());
}
```
希望对你有帮助。
阅读全文