当前位置:   article > 正文

Java SpringBoot实现导入导出Excel功能_springboot sheet导入模板带下拉框选

springboot sheet导入模板带下拉框选

在SpringBoot项目中实现导入导出EXCEL进行数据处理,可以使用Apache POI库来操作Excel文件。以下是实现步骤:

  1. 添加POI库依赖

在pom.xml文件中添加以下依赖:

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>4.1.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi-ooxml</artifactId>
  9. <version>4.1.2</version>
  10. </dependency>
  1. 导出Excel文件

在Controller中定义一个导出Excel的方法,该方法接收一个HttpServletResponse对象作为参数,并设置响应头信息,以便浏览器下载Excel文件。

  1. @GetMapping("/export")
  2. public void export(HttpServletResponse response) throws IOException {
  3. response.setContentType("application/vnd.ms-excel");
  4. response.setHeader("Content-Disposition", "attachment; filename=example.xlsx");
  5. Workbook workbook = new XSSFWorkbook();
  6. Sheet sheet = workbook.createSheet("Sheet1");
  7. // 往Excel中添加数据
  8. Row row = sheet.createRow(0);
  9. row.createCell(0).setCellValue("姓名");
  10. row.createCell(1).setCellValue("年龄");
  11. row = sheet.createRow(1);
  12. row.createCell(0).setCellValue("张三");
  13. row.createCell(1).setCellValue(20);
  14. row = sheet.createRow(2);
  15. row.createCell(0).setCellValue("李四");
  16. row.createCell(1).setCellValue(25);
  17. workbook.write(response.getOutputStream());
  18. workbook.close();
  19. }
  1. 导入Excel文件

在Controller中定义一个导入Excel的方法,该方法接收一个MultipartFile对象作为参数,并使用POI库读取Excel文件中的数据。

  1. @PostMapping("/import")
  2. public void importExcel(@RequestParam("file") MultipartFile file) throws IOException {
  3. Workbook workbook = WorkbookFactory.create(file.getInputStream());
  4. Sheet sheet = workbook.getSheetAt(0);
  5. for (Row row : sheet) {
  6. String name = row.getCell(0).getStringCellValue();
  7. int age = (int) row.getCell(1).getNumericCellValue();
  8. // 处理Excel中的数据
  9. }
  10. workbook.close();
  11. }

以上就是在SpringBoot项目中实现导入导出Excel进行数据处理的方法。需要注意的是,在实际开发中需要根据具体业务需求进行修改和完善。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/321483
推荐阅读
相关标签
  

闽ICP备14008679号