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

三、运行效果

相关推荐
身如柳絮随风扬2 小时前
Java中的CAS机制详解
java·开发语言
风筝在晴天搁浅3 小时前
hot100 78.子集
java·算法
故事和你914 小时前
sdut-Java面向对象-06 继承和多态、抽象类和接口(函数题:10-18题)
java·开发语言·算法·面向对象·基础语法·继承和多态·抽象类和接口
Configure-Handler4 小时前
buildroot System configuration
java·服务器·数据库
:Concerto5 小时前
JavaSE 注解
java·开发语言·sprint
电商API_180079052475 小时前
第三方淘宝商品详情 API 全维度调用指南:从技术对接到生产落地
java·大数据·前端·数据库·人工智能·网络爬虫
一点程序6 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
C雨后彩虹6 小时前
计算疫情扩散时间
java·数据结构·算法·华为·面试
2601_949809596 小时前
flutter_for_openharmony家庭相册app实战+我的Tab实现
java·javascript·flutter
vx_BS813306 小时前
【直接可用源码免费送】计算机毕业设计精选项目03574基于Python的网上商城管理系统设计与实现:Java/PHP/Python/C#小程序、单片机、成品+文档源码支持定制
java·python·课程设计