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

三、运行效果

相关推荐
huaweichenai10 小时前
java的数据类型介绍
java·开发语言
weisian15110 小时前
Java并发编程--17-阻塞队列BlockingQueue:生产者-消费者模式的最佳实践
java·阻塞队列·blockqueue
奔跑的呱呱牛10 小时前
GeoJSON 在大数据场景下为什么不够用?替代方案分析
java·大数据·servlet·gis·geojson
爱丽_10 小时前
Pinia 状态管理:模块化、持久化与“权限联动”落地
java·前端·spring
luom010211 小时前
SpringBoot - Cookie & Session 用户登录及登录状态保持功能实现
java·spring boot·后端
黄俊懿11 小时前
【架构师从入门到进阶】第二章:系统衡量指标——第一节:伸缩性、扩展性、安全性
分布式·后端·中间件·架构·系统架构·架构设计
毕设源码-朱学姐11 小时前
【开题答辩全过程】以 骨科术后营养餐推荐系统为例,包含答辩的问题和答案
java
丶小鱼丶11 小时前
数据结构和算法之【栈】
java·数据结构
希望永不加班11 小时前
SpringBoot 核心配置文件:application.yml 与 application.properties
java·spring boot·后端·spring
散峰而望11 小时前
【基础算法】从入门到实战:递归型枚举与回溯剪枝,暴力搜索的初级优化指南
数据结构·c++·后端·算法·机器学习·github·剪枝