Excel导出 并返回已封装的对象出现的问题 no converter

项目场景:

例如:项目场景:导出Excel报错 但不影响功能


问题描述

例如:导出Excel的时候setContentType(“application/vnd.ms-excel”)
并且返回自定义的Result时报错但不影响功能。(无论是否成功都会报错)

try {
     response.setContentType("application/vnd.ms-excel");
     response.setCharacterEncoding("utf-8");
     response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
     EasyExcel.write(response.getOutputStream(), t).sheet("模板").doWrite(data);
     return 1;
 }catch (IOException e){
     e.printStackTrace();
     return 0;
 }
 ---------------------------
if (code == 1) {
     return AjaxResult.success(fileName);
} else {
     return AjaxResult.error("导出失败!");
}
----------------------------
exception: No converter for [class xxxxxx] with preset Content-Type 'application/vnd.ms-excel;charset=UTF-8']

原因分析:

没有转换器,
内含内含预设的内容类型[’application/vnd.ms-excel;charset=UTF-8’]


解决方案:

  1. 返回空 void
  2. 配置fastjson消息转换器
    WebMvcConfigurer->configureMessageConverters
@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //调用父类的配置
        WebMvcConfigurer.super.configureMessageConverters(converters);
        //创建FastJson的消息转换器
        FastJsonHttpMessageConverter convert = new FastJsonHttpMessageConverter();
        //创建FastJson的配置对象
        FastJsonConfig config = new FastJsonConfig();
        //对Json数据进行格式化
        config.setSerializerFeatures(SerializerFeature.PrettyFormat,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteMapNullValue,
                //禁止循环引用
                SerializerFeature.DisableCircularReferenceDetect);
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setCharset(StandardCharsets.UTF_8);
        convert.setFastJsonConfig(config);
        convert.setSupportedMediaTypes(getSupportedMediaTypes());
        converters.add(convert);
    }

    public List<MediaType> getSupportedMediaTypes() {
        //创建fastJson消息转换器
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.IMAGE_GIF);
        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
        supportedMediaTypes.add(MediaType.IMAGE_PNG);
        supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        supportedMediaTypes.add(MediaType.TEXT_XML);
        supportedMediaTypes.add(MediaType.ALL); //主要是这里
        return supportedMediaTypes;
    }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,那么您可以使用Apache POI库来实现Excel导出,同将生成的Excel文件的字节数组(即Blob)封装到一个JsonObject对象中,然后返回对象给前端。 具体实现步骤如下: 1. 后端使用Apache POI库创建Excel文件并写入数据。 2. 在Controller中定义一个导出Excel的接口,使用JsonObject对象封装Excel文件的字节数组和其他相关信息。 3. 将JsonObject对象转换成字符串后,使用ResponseEntity将其写入响应体中,并设置Content-Type为application/json,这样前端就可以通过解析响应体得到Excel文件的字节数组和其他相关信息。 4. 如果导出Excel遇到异常,可以使用try-catch语句捕获异常,并将异常信息封装JsonObject对象返回给前端。 下面是一个简单的示例代码,仅供参考: ```java @RestController public class ExcelController { @GetMapping("/exportExcel") public ResponseEntity<String> exportExcel() { JsonObject result = new JsonObject(); try { // 使用Apache POI创建Excel文件并写入数据 Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet("sheet1"); Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("Hello World!"); ByteArrayOutputStream out = new ByteArrayOutputStream(); wb.write(out); // 将生成的Excel文件的字节数组封装JsonObject对象中 result.addProperty("success", true); result.addProperty("message", "导出Excel成功"); result.addProperty("fileName", "example.xls"); result.addProperty("fileContent", Base64.getEncoder().encodeToString(out.toByteArray())); // 将JsonObject对象转换成字符串并返回给前端 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<>(result.toString(), headers, HttpStatus.OK); } catch (Exception e) { // 如果导出Excel遇到异常,将异常信息封装JsonObject对象返回给前端 result.addProperty("success", false); result.addProperty("message", "导出Excel失败:" + e.getMessage()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<>(result.toString(), headers, HttpStatus.INTERNAL_SERVER_ERROR); } } } ``` 在前端中,您可以使用axios或其他HTTP库来调用后端的导出Excel接口,例如: ```javascript axios.get('/exportExcel') .then(response => { if (response.data.success) { // 导出Excel成功,使用Blob对象创建一个URL并下载Excel文件 let url = URL.createObjectURL(base64ToBlob(response.data.fileContent)); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.setAttribute('download', response.data.fileName); document.body.appendChild(link); link.click(); } else { // 导出Excel失败,展示错误信息 console.error(response.data.message); alert('导出Excel失败'); } }) .catch(error => { // 调用导出Excel接口失败,展示错误信息 console.error(error); alert('调用导出Excel接口失败'); }); function base64ToBlob(base64String) { let byteCharacters = atob(base64String); let byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } let byteArray = new Uint8Array(byteNumbers); return new Blob([byteArray]); } ``` 这样就可以实现将生成的Excel文件的字节数组封装JsonObject对象中,然后返回对象给前端的功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值