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));
    }
}

三、运行效果

相关推荐
无限的鲜花8 小时前
反射(原创推荐)
java·开发语言
IT二叔9 小时前
Java项目部署-03-teamcity-cicd-docker镜像流水线方式部署
java·ci/cd·持续部署
一路向北he9 小时前
字节钢铁军团--“提供情境,而非控制”
java·开发语言·前端
码事漫谈9 小时前
别写Prompt了,现在流行给AI“写循环”
后端
超级数据查看器9 小时前
超级数据查看器 v10.0 发布
java·大数据·数据库·sqlite·安卓
Kyrie_Li10 小时前
Spring Boot Kafka 生产级配置全解析:从入门到精通
spring boot·后端·kafka
Coder_Shenshen10 小时前
西门子S7CommPlus协议鉴权算法原理与流程详解
网络·后端·算法
折哥的程序人生 · 物流技术专研11 小时前
《Java 100 天进阶之路》第50篇:阻塞队列与并发容器(2026版)
java·面试题·java进阶·blockingqueue·并发容器·集合源码·java100天进阶
ai_coder_ai11 小时前
编写自动化脚本,在自己后端服务中使用Open Api进行设备相关操作
java·运维·自动化
yuhaiqiang11 小时前
随手 vibecoding 的浏览器插件已经 6000 多次下载,聊聊他的产品设计
前端·后端·面试