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

三、运行效果

相关推荐
失散136 分钟前
架构师级别的电商项目——2 电商项目核心需求分析
java·分布式·微服务·架构·需求分析
麦兜*8 分钟前
Redis内存消耗异常飙升?深入排查与Big Key/Hot Key的根治方案
jvm·数据库·spring boot·redis·spring·缓存
MediaTea40 分钟前
Python 第三方库:Flask(轻量级 Web 框架)
开发语言·前端·后端·python·flask
Kuo-Teng43 分钟前
LeetCode 198: House Robber
java·算法·leetcode·职场和发展·动态规划
q***72561 小时前
Spring Boot + Vue 全栈开发实战指南
vue.js·spring boot·后端
小七mod1 小时前
【Spring】Spring Boot自动配置的案例
java·spring boot·spring·自动配置·源码·ioc·aop
java干货1 小时前
Spring Boot 为什么“抛弃”了 spring.factories?
spring boot·python·spring
红石榴花生油1 小时前
Docker + Nginx 部署 Java 项目(JAR 包 + WAR 包)实战笔记
java·tomcat·maven
清晨细雨~1 小时前
SpringBoot整合EasyExcel实现Excel表头校验
spring boot·后端·excel
带刺的坐椅1 小时前
Solon AI 开发学习 - 1导引
java·ai·openai·solon·mcp