赞
踩
在SpringBoot项目中实现导入导出EXCEL进行数据处理,可以使用Apache POI库来操作Excel文件。以下是实现步骤:
在pom.xml文件中添加以下依赖:
- <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>
在Controller中定义一个导出Excel的方法,该方法接收一个HttpServletResponse对象作为参数,并设置响应头信息,以便浏览器下载Excel文件。
- @GetMapping("/export")
- public void export(HttpServletResponse response) throws IOException {
- response.setContentType("application/vnd.ms-excel");
- response.setHeader("Content-Disposition", "attachment; filename=example.xlsx");
- Workbook workbook = new XSSFWorkbook();
- Sheet sheet = workbook.createSheet("Sheet1");
- // 往Excel中添加数据
- Row row = sheet.createRow(0);
- row.createCell(0).setCellValue("姓名");
- row.createCell(1).setCellValue("年龄");
- row = sheet.createRow(1);
- row.createCell(0).setCellValue("张三");
- row.createCell(1).setCellValue(20);
- row = sheet.createRow(2);
- row.createCell(0).setCellValue("李四");
- row.createCell(1).setCellValue(25);
- workbook.write(response.getOutputStream());
- workbook.close();
- }

在Controller中定义一个导入Excel的方法,该方法接收一个MultipartFile对象作为参数,并使用POI库读取Excel文件中的数据。
- @PostMapping("/import")
- public void importExcel(@RequestParam("file") MultipartFile file) throws IOException {
- Workbook workbook = WorkbookFactory.create(file.getInputStream());
- Sheet sheet = workbook.getSheetAt(0);
- for (Row row : sheet) {
- String name = row.getCell(0).getStringCellValue();
- int age = (int) row.getCell(1).getNumericCellValue();
- // 处理Excel中的数据
- }
- workbook.close();
- }
以上就是在SpringBoot项目中实现导入导出Excel进行数据处理的方法。需要注意的是,在实际开发中需要根据具体业务需求进行修改和完善。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。