直接下载SpringBoot项目本地的Excel文件

1.Excel文件放在src/man/resources/templates下;

2.修改pom.xml文件中的maven打包方式

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<version>2.6</version>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
</build>

3.创建相应的Controller


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ResourceLoader;
import java.nio.charset.StandardCharsets;

@RestController
@Api(tags = "下载模板")
@RequestMapping("download")
@Slf4j
public class DownloadController {

@Resource
private ResourceLoader resourceLoader;

@ApiOperation(value = "模板1", httpMethod = "GET")
@GetMapping("template")
public void downloadBlacklistTemplate(HttpServletRequest request, HttpServletResponse response){
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
try {
String filename = "template.xlsx";
String path = "templates/template.xlsx";
org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:"+path);

response.setContentType("application/vnd.ms-excel");
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("charset", "utf-8");
response.addHeader("Pragma", "no-cache");
String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
response.setHeader("Content-Disposition", "attachment; filename="" + encodeName + ""; filename*=utf-8''" + encodeName);

inputStream = resource.getInputStream();
servletOutputStream = response.getOutputStream();
IOUtils.copy(inputStream, servletOutputStream);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
servletOutputStream = null;
}
if (inputStream != null) {
inputStream.close();
inputStream = null;
}
// 召唤jvm的垃圾回收器
System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

4.运行项目
原文地址:https://www.cnblogs.com/liping0720/p/13963529.html