欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > EasyExcel 学习之 导出 “提示问题”

EasyExcel 学习之 导出 “提示问题”

2025/9/26 10:42:04 来源:https://blog.csdn.net/DreamStar2560/article/details/143558478  浏览:    关键词:EasyExcel 学习之 导出 “提示问题”

EasyExcel 学习之 导出 “提示问题”

  • 现象
  • 分析
  • 解决(伪代码)
    • 前端 POST 实现
    • 后端实现

现象

EasyExcel 支持导出 xlsxxlscsv 三种文件格式。在导出过程中可能发生各种异常,当发生异常时应该提示错误信息而非导出一个错误的文件。

分析

  • 首先,后端应该支持两种不同格式(content-type)内容的返回
  • 其次,前端应该支持两种不同格式(content-type)内容的解析处理

解决(伪代码)

前端 POST 实现

const axios = require('axios');axios({url: 'https://api.example.com/export',method: 'post',data: {param1: 'value1',param2: 'value2'},responseType: 'blob',headers: {'Authorization': 'Bearer YOUR_TOKEN'}
})
.then(response => {if (response.data && response.data.type == 'application/json') {const render = new FileReader();reader.onload = (e) => {let content = e.target.result;content = JSON.parse(content);this.$antMessage.info(content.msg);}} else {var blob = new Blob([response.data]);const url = window.URL.createObjectURL(blob);const link = document.createElement('a');link.style.display = 'none';link.href = url;link.setAttribute('download', name);document.body.appendChild(link);link.click();document.body.removeChild(link);}
})
.catch(error => {console.error('Error:', error);
});

后端实现

if (errorCondition) {throw new BusinessException('errorCode', 'errorMsg');
}response.setContentType(ExcelConst.MEDIA_TYPE_EXCEL);
response.setHeader(ExcelConst.CONTENT_DISPOSITION, String.format("%s:%s=%s.%s", ExcelConst.ATTACHMENT, ExcelConst.FILENAME, System.currentTimeMillis(), ExcelTypeEnum.XLSX.getValue()));try (OutputStream os = response.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream()) {ExcelWriter excelWriter = EasyExcel.write(baos).charset(Charset.forName("GBK")) // 或者 UTF-8.autoCloseStream(true).excludeColumnFieldNames(Lists.newArrayList()).excelType(ExcelTypeEnum.XLSX).build();WriteSheet writeSheet = EasyExcel.writerSheet(sheetNo, sheetName).head(clazz).build();excelWriter.write(sheetData, writeSheet);excelWriter.finish();os.write(baos.toByteArray());
} catch (Exception e) {log.error(String.format("Excel 导出失败!%s", ""), e);
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词