当前位置:   article > 正文

springboot项目resource导出excel模板问题_获取resource下的excel模板导出

获取resource下的excel模板导出

excel模板位于resource下面时

直接用文件流导出

    public void getTemplate(HttpServletRequest request, HttpServletResponse response) {
        try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/template.xls");
             OutputStream out = response.getOutputStream()
        ){
            if (inputStream == null) {
                throw  new GlobalException("模板不存在!");
            }

            response.setContentType("application/octet-stream");
            String fileName = URLEncoder.encode("模板","utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
            response.setContentType("application/vnd.ms-excel ;charset=UTF-8");
            byte[] bytes = new byte[1024 * 2];
            while(inputStream.read(bytes) != -1){
                out.write(bytes);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw  new GlobalException("导出失败!");
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

结果会文件损坏,或乱码,如下图
请添加图片描述

原因分析-sprintboot默认会压缩resource下的excel

解决方法

pom文件的build下添加关闭压缩配置

		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<version>2.6</version>
			<artifactId>maven-resources-plugin</artifactId>
			<configuration>
				<encoding>UTF-8</encoding>
				<nonFilteredFileExtensions>
					<nonFilteredFileExtension>xls</nonFilteredFileExtension>
					<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
				</nonFilteredFileExtensions>
			</configuration>
		</plugin>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/815917
推荐阅读
相关标签
  

闽ICP备14008679号