Java 下载excle模板问题记录

项目场景:

在编写后台信息excle导入功能,需要先提供excle模板下载功能


问题描述:

在编写excle模板下载功能时,遇到以下问题:

  1. Failed to read zip entry source
  2. 导出excle模板名称乱码
  3. No converter for with preset Content-Type ‘multipart/form-data’

原因分析及解决方案:

第一个问题

查看错误日志,提示IOException异常,excel模板在项目打包编译时,xlsx文件解压缩时出问题;
去target目录下查看,excel打不开,提示文件损坏

解决办法:在pom文件中加入以下配置即可避免此问题

<plugins>
	<plugin>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-maven-plugin</artifactId>
		<version>${spring-boot.version}</version>
	</plugin>
	<!-- 过滤后缀文件 -->
	<plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-resources-plugin</artifactId>
		<configuration>
			<nonFilteredFileExtensions>
				<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
				<nonFilteredFileExtension>xls</nonFilteredFileExtension>
			</nonFilteredFileExtensions>
		</configuration>
	</plugin>
</plugins>

第二个问题

没有指定编码格式,或浏览器原因

解决办法:代码中对文件名处理编码格式,request区分浏览器

String fileName = "导入模板.xlsx";
String agent = request.getHeader("USER-AGENT").toLowerCase();
if (agent.contains("firefox")) {
    response.reset();
    response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment;filename="
            + new String(fileName.getBytes(), "ISO8859-1"));
} else {
    fileName = URLEncoder.encode(fileName, "UTF-8");
    response.reset();
    // ContentType 可以不设置
    response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
}

第三个问题

下载模板成功,但是后台一直报错java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
[response被提交后不能调用sendError()]

输出流关闭之后调用return导致的这个错误

@RequestMapping(value = "/downloadExcel")
public ApiResult downloadExcel(HttpServletRequest request, HttpServletResponse response) {
    // 模板位置
    OutputStream os = null;
    try (InputStream bis = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("statics/js/modules/excelTemplate/distributorTemp.xlsx")) {
        String fileName = "导入模板.xlsx";
        String agent = request.getHeader("USER-AGENT").toLowerCase();
        if (agent.contains("firefox")) {
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes(), "ISO8859-1"));
        } else {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            // ContentType 可以不设置
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        }
        // 读取excel模板
        XSSFWorkbook wb = new XSSFWorkbook(bis);
        os = new BufferedOutputStream(response.getOutputStream());
        wb.write(os);
        os.flush();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
        return ApiResult.error("下载模板出错:" + e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return ApiResult.ok();
}

解决方法:将返回值改为void或者return null

创作不易,关注、点赞就是对作者最大的鼓励,欢迎在下方评论留言
欢迎关注微信公众号:键指JAVA,定期分享Java知识,一起学习,共同成长。

posted on 2022-06-09 23:18  猫的树kireCat  阅读(302)  评论(0编辑  收藏  举报