SpringBoot下载Excel模板功能

目录

一、前端只需要填写一个a标签调用一下后端接口即可

二、后端

[2.1 准备一个excel模板 ,将其复制到resource目录下的templates文件夹下](#2.1 准备一个excel模板 ,将其复制到resource目录下的templates文件夹下)

[2.2 接着复制下列代码即可](#2.2 接着复制下列代码即可)

三、运行效果


一、前端只需要填写一个a标签调用一下后端接口即可

1.1 先代理一下防止跨域

TypeScript 复制代码
export default defineConfig({
  plugins: [vue()],
  server: {
    port: 5000,
    proxy: {
      "/api": { target: "http://localhost:8080/", changeOrigin: true },
    },
  },

});

2.2 调用后端接口

二、后端

2.1 准备一个excel模板 ,将其复制到resource目录下的templates文件夹下

2.2 接着复制下列代码即可

java 复制代码
package com.beiyou.controller;


import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api")
public class DownloadController {

    @GetMapping("/downloadExcelTemplate")
    public ResponseEntity<InputStreamResource> downloadExcelTemplate() throws Exception {
        // 模板文件路径
        String templateFilePath = "/templates/123.xls";
        
        // 获取资源文件输入流
        ClassPathResource resource = new ClassPathResource(templateFilePath);
        InputStream inputStream = resource.getInputStream();

        // 设置响应头,包括文件名和MIME类型
        String filename = "模板.xlsx";
        String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", encodedFilename);

        // 返回包含文件流的ResponseEntity对象
        return ResponseEntity.ok()
                .headers(headers)
                .body(new InputStreamResource(inputStream));
    }
}

三、运行效果

相关推荐
IT_陈寒12 小时前
SpringBoot自动配置的坑,我的API突然就404了
前端·人工智能·后端
ServBay12 小时前
为什么说 MCP 是 2026 年开发者必须掌握的黄金协议?
后端·mcp
程序员夏洛12 小时前
Spring Boot 多模块项目中 IDEA 提示 Cannot resolve symbol 的一次排查记录
后端
子兮曰12 小时前
OpenMontage 深度解剖:你的 AI 编程助手,其实是个视频工作室
前端·后端·ai编程
子兮曰13 小时前
前端工具链的「Rust 化」:一场没有赢家的军备竞赛?
前端·后端·rust
爱勇宝14 小时前
从 Ctrl+CV 到 Enter:程序员正在失去什么
前端·后端·程序员
码事漫谈14 小时前
EdgeOne Makers + WorkBuddy:零基础也能快速搭建可上线的 AI 智能体(附图文教程)
后端
像我这样帅的人丶你还14 小时前
Java 后端详解(四):分页与搜索
java·javascript·后端
她的男孩15 小时前
数据权限为什么不能只靠注解?Forge 的 Mapper 层 SQL 改写源码拆解
java·后端·架构