在实际运用中,数据导入,会遇到模板下载,但是下载后,Excel文件损坏无法打开
模板位置
下载代码
@PostMapping("/downloadExcel")
public void downloadExcel(HttpServletResponse response) {
try {
ClassPathResource resource = new ClassPathResource("excel" + File.separator + "限制出卡模板.xlsx");
// 获取文件
File file = resource.getFile();
logger.info("文件名称:{}", file.getName());
String fileName = "payCardLimit" + DateUtil.getTimeFormat(new Date()) + ".xlsx";
// 配置文件下载
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("Download successfully!");
} catch (Exception e) {
System.out.println("Download failed!");
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
会出现以下错误
解决办法,在pom中增加
<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>
clean 重启即可。