2025.4.15写项目 springboot导入导出excel表和完成接口

今天写后端接口,花了很久的时间去读接口文档,和队友的代码,最后完成第一个子模块前两个后端接口,经postman测试,样例符合接口文档预期

以下为简单的后端excel导入导出模板
/**
* excel 文件导入接口
* @param file excel文件
* @throws Exception
*/
@PostMapping("/import")
public void imp(@RequestBody MultipartFile file) throws Exception {
//1.使用 inputStream 流读取文件
InputStream inputStream = file.getInputStream();
//2.读取流中的数据
ExcelReader reader =ExcelUtil.getReader(inputStream);
//3.将汲取到的数据填充为List
List users=reader.readAll(User.class);
//4. 将List导入数据库
userRepository.saveAll(users);

}

/**
 * excel导出接口
 * @param response
 * @param user
 * @throws Exception
 */

@GetMapping("/export")
public void export(HttpServletResponse response,User user) throws Exception {
    //1.从数据库中查询所有的user数据
    List<User> users = userRepository.findAll();

    //2.通过工具类将文件写出到浏览器
    ExcelWriter writer = ExcelUtil.getWriter(true);

    //3.写入数据
    writer.write(users, true);

    //4.设置响应头 - 修正部分
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

    // 正确设置文件名编码(只需编码一次)
    String fileName = "用户信息.xlsx";
    String encodedFileName = URLEncoder.encode(fileName, "UTF-8")
            .replaceAll("\\+", "%20"); // 替换+号为%20以兼容更多浏览器

    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + encodedFileName + "\";" +
                    "filename*=UTF-8''" + encodedFileName);

    //5.输出流
    ServletOutputStream out = response.getOutputStream();
    writer.flush(out, true);
    out.close();
    writer.close();
}

以下为前端内容

posted @ 2025-04-15 23:51  臧博涛  阅读(386)  评论(0)    收藏  举报