springboot实现excel文件下载

1.项目结构(Excel模板地址)

2.后端代码

其中ClassPathResource为org.springframework.core.io.ClassPathResource;

    /**
     * 工时Excel模板下载
     * @param response
     */
    @RequestMapping("/workHoursExcel")
    public void downloadWorkHourRecordTemplate(HttpServletResponse response) {
        try {
            Resource resource = new ClassPathResource("WorkHoursRecordTemplate/Excel批量导入工时模板.xlsx");
            File file = resource.getFile();
            String filename = resource.getFilename();
            InputStream inputStream = new FileInputStream(file);
            //强制下载不打开
            response.setContentType("application/force-download");
            OutputStream out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) {
                    out.write(buffer, 0, b);
                }
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.前端

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中,你可以使用 Apache POI 库来实现 Excel 文件的读取和导入数据。以下是一个简单的示例: 1. 添加 Maven 依赖 ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建 Excel 文件模板 首先,你需要创建一个 Excel 文件模板,其中包含要导入的数据的列。 3. 创建 POJO 类 你需要创建一个 POJO 类来表示要导入的数据。该类的属性应该与 Excel 文件中的列相对应。 4. 编写读取 Excel 文件的代码 ```java @Service public class ExcelService { public List<YourPOJO> readExcel(MultipartFile file) throws IOException, InvalidFormatException { Workbook workbook = WorkbookFactory.create(file.getInputStream()); Sheet sheet = workbook.getSheetAt(0); List<YourPOJO> list = new ArrayList<>(); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); YourPOJO pojo = new YourPOJO(); pojo.setProp1(row.getCell(0).getStringCellValue()); pojo.setProp2(row.getCell(1).getStringCellValue()); // ... list.add(pojo); } return list; } } ``` 5. 编写控制器代码 ```java @RestController public class YourController { @Autowired private ExcelService excelService; @PostMapping("/import-excel") public ResponseEntity<Void> importExcel(@RequestParam("file") MultipartFile file) throws IOException, InvalidFormatException { List<YourPOJO> list = excelService.readExcel(file); // 处理导入的数据 return ResponseEntity.ok().build(); } } ``` 这样,当你上传 Excel 文件时,它将被读取并转换为一个包含 YourPOJO 对象的列表,你可以使用它们来执行进一步的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值