You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot返回Excel时报No converter for [class [B] Content-Type null错误如何解决

问题原因
  • MIME类型匹配错误:XSSFWorkbook对应Office 2007及以上的.xlsx格式,你配置的application/vnd.ms-excel是旧版.xls(对应HSSFWorkbook)的MIME类型,类型不匹配导致SpringMVC的消息转换器无法正常识别处理。
  • ResponseEntity返回时未显式绑定响应头的Content-Type:虽然接口注解配置了produces,但返回字节数组时部分SpringBoot版本会出现消息转换器匹配异常,无法自动读取注解的produces配置,出现提示的Content-Type 'null'错误。
解决方案
  1. 修正MIME类型,替换为.xlsx对应的正确类型:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  2. 构造ResponseEntity时显式指定响应头,包括Content-Type和下载所需的Content-Disposition头,避免文件名乱码和格式识别异常

修改后的完整代码如下:

@GetMapping(value = "/download", produces = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
public ResponseEntity<byte[]> downloadExcel(@RequestParam String param) throws IOException {
    XSSFWorkbook workbook = service.createExcel(param);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    workbook.write(stream);
    workbook.close();
    // 构造响应头
    HttpHeaders headers = new HttpHeaders();
    // 显式指定Content-Type
    headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
    // 指定下载文件名,编码处理避免中文乱码
    String fileName = URLEncoder.encode("导出数据.xlsx", "UTF-8").replaceAll("\\+", "%20");
    headers.setContentDispositionFormData("attachment", fileName);
    return ResponseEntity.ok()
            .headers(headers)
            .body(stream.toByteArray());
}
验证注意事项
  • Postman调用接口时,选择「Send and Download」按钮而非直接点击Send,直接Send会将字节流以文本形式展示,看起来就是乱码,选择下载后可直接得到正常的xlsx文件。
  • 如果项目用的是HSSFWorkbook生成.xls格式,再改回application/vnd.ms-excel的MIME类型即可。

内容的提问来源于stack exchange,提问作者KarinaMz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:18:05