springboot vue导出excel

处理后端返回的文件流,下载成excl文件

vue

<el-button class="el-icon-download" type="success" @click="exportExcel()">导出</el-button>

没封装axios

exportExcel() {axios({url: 请求地址, //URL,根据实际情况来method: "get", responseType: "blob" //这里必须设置 responseType: "blob"}).then(function (res) {const link = document.createElement("a");let blob = new Blob([res.data], { type: res.data.type });// let blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); //知道type也可以直接填link.style.display = "none";//设置连接let url = URL.createObjectURL(blob);link.href = url;//导出文件名称link.download = "客户表格"; //模拟点击事件link.click();document.body.removeChild(link);});}

没封装axios的请求返回值res let blob = new Blob([res.data], { type: res.data.type }); 这里的res.data 或者 res.data.type 必须和这里对应

导出表格内容可能显示【Object object】或者 undefined 大概率这里填的有误

封装axios

export function exportUser(params) {return service({url: "/xxx", //自己后台请求地址method: "get",responseType: 'blob',   //这里必须设置 responseType: "blob"params: params});
}
   async exportExcel() {const res = await exportExcel();if (res) {const link = document.createElement("a");let blob = new Blob([res], { type: res.type });link.style.display = "none";//设置连接link.href = URL.createObjectURL(blob);link.download = "客户表格";document.body.appendChild(link);//模拟点击事件link.click();document.body.removeChild(link);}}

封装过的返回值可能不一样 let blob = new Blob([res], { type: res.type }); 这里就填写对应的 返回值

后端

用的easypoi

首先引入pom依赖

   <!--easypoi导入导出--><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>4.1.3</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-web</artifactId><version>4.1.3</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-annotation</artifactId><version>4.1.3</version></dependency>

编写实体类

@ExcelTarget("user")
@Data
public class User {private Integer id;/*** 邮箱*/@Excel(name = "邮箱")private String mailbox;/*** 用户名*/@Excel(name = "用户名")private String userName;@Excel(name = "ip")private String ip;@Excel(name = "备注")private String remarks;

这里使用了 @Excel 是关键注解,必不可少,name表示指定生成的excel的对应列明,更多用法请求官方文档查看或者百度使用。

控制层

    @GetMapping(value = "/getUser")public void getUser(HttpServletResponse response) {List<User> users  = userService.getUser();Workbook workbook = null;ServletOutputStream outputStream = null;try {workbook = ExcelExportUtil.exportExcel(new ExportParams("表格首行名称", "sheet名称"), User.class, users);response.setCharacterEncoding("utf-8");response.setContentType("application/vnd.ms-excel;charset=utf-8");response.setHeader("content-Disposition", "attachment;fileName="+ URLEncoder.encode("导出excel名称", "UTF-8"));//  出现跨域问题 可以加这俩行  //    response.setHeader("Access-Control-Allow-Origin", "前台地址");//  response.setHeader("Access-Control-Allow-Credentials", "true");outputStream = response.getOutputStream();workbook.write(outputStream);outputStream.flush();} catch (IOException e) {e.printStackTrace();} finally {try {outputStream.close();workbook.close();} catch (IOException e) {e.printStackTrace();}}// 或者直接用封装好的工具类 网上也有很多的// ExcelUtil.exportExcel(数据list, "表格首行名称", "sheet名称", User.class, "导出excel名称", response);}

excel能够正常导出 打开也没有乱码 但是控制台可能会报错

org.springframework.http.converter.HttpMessageNotWritableException: No converter for [xxx] with preset Content-Type 'application/vnd.ms-excel;charset=utf-8'

controller的方法用放回值 方法 改成void即可

工具类

public class ExcelUtil {/*** Map集合导出** @param list     需要导出的数据* @param fileName 导出的文件名* @param response HttpServletResponse对象*/public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws Exception{defaultExport(list, fileName, response);}/*** 复杂导出Excel,包括文件名以及表名(不创建表头)** @param list      需要导出的数据* @param title     表格首行标题(不需要就传null)* @param sheetName 工作表名称* @param pojoClass 映射的实体类* @param fileName  导出的文件名(如果为null,则默认文件名为当前时间戳)* @param response  HttpServletResponse对象*/public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,HttpServletResponse response) throws Exception{defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));}/*** 复杂导出Excel,包括文件名以及表名(创建表头)** @param list           需要导出的数据* @param title          表格首行标题(不需要就传null)* @param sheetName      工作表名称* @param pojoClass      映射的实体类* @param fileName       导出的文件名* @param isCreateHeader 是否创建表头* @param response       HttpServletResponse对象*/public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,boolean isCreateHeader, HttpServletResponse response) throws Exception{ExportParams exportParams = new ExportParams(title, sheetName);exportParams.setCreateHeadRows(isCreateHeader);defaultExport(list, pojoClass, fileName, response, exportParams);}/*** 默认导出方法** @param list         需要导出的数据* @param pojoClass    对应的实体类* @param fileName     导出的文件名* @param response     HttpServletResponse对象* @param exportParams 导出参数实体*/private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response,ExportParams exportParams) throws Exception{Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);downloadExcel(fileName, workbook, response);}/*** 默认导出方法** @param list     Map集合* @param fileName 导出的文件名* @param response HttpServletResponse对象*/private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response)throws Exception {Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);if (null != workbook) {downloadExcel(fileName, workbook, response);}}/*** Excel导出** @param fileName Excel导出* @param workbook Excel对象* @param response HttpServletResponse对象*/public static void downloadExcel(String fileName, Workbook workbook, HttpServletResponse response) throws Exception{ServletOutputStream outputStream = null;try {if (StringUtils.isEmpty(fileName)) {throw new RuntimeException("导出文件名不能为空");}response.setCharacterEncoding("utf-8");response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");response.setHeader("content-disposition", "attachment;fileName="+ URLEncoder.encode(fileName+".xls", "UTF-8"));//          response.setHeader("Access-Control-Allow-Origin", "前台ip");
//          response.setHeader("Access-Control-Allow-Credentials", "true");outputStream = response.getOutputStream();workbook.write(outputStream);outputStream.flush();} catch (Exception e) {log.error(e.getMessage(), e);} finally {outputStream.close();workbook.close();}}/*** 根据文件路径来导入Excel** @param filePath   文件路径* @param titleRows  表标题的行数* @param headerRows 表头行数* @param pojoClass  映射的实体类* @return*/public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception{//判断文件是否存在if (StringUtils.isBlank(filePath)) {return null;}ImportParams params = new ImportParams();params.setTitleRows(titleRows);params.setHeadRows(headerRows);List<T> list = null;try {list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);} catch (NoSuchElementException e) {log.error("模板不能为空", e);} catch (Exception e) {log.error(e.getMessage(), e);}return list;}/*** 根据接收的Excel文件来导入Excel,并封装成实体类** @param file       上传的文件* @param titleRows  表标题的行数* @param headerRows 表头行数* @param pojoClass  映射的实体类* @return*/public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception{if (file == null) {return null;}ImportParams params = new ImportParams();params.setTitleRows(titleRows);params.setHeadRows(headerRows);List<T> list = null;try {list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);} catch (NoSuchElementException e) {log.error("excel文件不能为空", e);} catch (Exception e) {log.error(e.getMessage(), e);}return list;}/*** 文件转List** @param file* @param pojoClass* @param <T>* @return*/public static <T> List<T> fileToList(MultipartFile file, Class<T> pojoClass) throws Exception{if (file.isEmpty()) {throw new RuntimeException("文件为空");}List<T> list = ExcelUtil.importExcel(file, 1, 1, pojoClass);if (CollectionUtils.isEmpty(list)) {throw new RuntimeException("未解析到表格数据");}return list;}
}

springboot vue导出excel 使用easypoi相关推荐

  1. vue导出excel加一个进度条_vue导出excel遇到的问题解决方法

    本篇文章给大家带来的内容是关于vue导出excel遇到的问题解决方法,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 需求: Vue+element UI el-table下的导出当前 ...

  2. springboot项目导出excel 合并单元格表格

    springboot项目导出excel 合并单元格表格 导出效果 业务controller 业务数据 业务实体类 注解MyExcel.java 注解 MyExcels 导出工具类MyExcelUtil ...

  3. (vue)vue导出excel文件打不开,或者文件内容为object object

    (vue)vue导出excel文件打不开,或者文件内容为object object[已解决] bug: 主要原因:没有注意到后端返回的数据格式,需要的是res而不是res.data 正确写法: < ...

  4. vue导出excel功能实现

    vue导出excel功能实现 第一步安装依赖包 第二步在项目中assets创建一个新的文件夹js用于存放Blob和Export2Excel两个js文件 第三步在你那个组件中使用 写事件方法 Expor ...

  5. 封装vue导出excel组件(扩展嵌入图片、操作工作表、表格样式等功能)

    导出的excel中嵌入图片,同时还需要操作多个工作表与表格样式, 看了一些java的插件不太适合,因为我这边的需求是动态表单,字段不固定.后端的插件大部分依赖实体类注解,要不就是操作比较繁琐.又看了一 ...

  6. vue导出excel表的时候有多张图片

    vue导出excel的时候多张图片 遇到数据结构是[ { id:id, image:['图片','图片','图片'] } ] 这样的数据导出,使用插件 js-table2excel 导出的时候发现它只 ...

  7. vue导出Excel表格全局函数(简洁明了)

    vue导出excel全局函数(简洁明了) 将导出到Excel功能封装成一个公用js函数,供其他vue页面复用. 1.安装Excel插件 npm install --save xlsx file-sav ...

  8. SpringBoot图文教程9—SpringBoot 导入导出 Excel 「Apache Poi」(亲测)

    有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 来源:Springboot使用POI实现导出Excel文件示例的搜索结果-阿里云开 ...

  9. SpringBoot图文教程9—SpringBoot 导入导出 Excel 「Apache Poi」

    有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1「概念+ ...

  10. Springboot 导入导出Excel ,一对多关系,复合表格、合并单元格数据

    前言 学习是自己的事. 但是跟着我学习,也未尝不可. 这种一对多的导出需求,好像确实也是比较常见的: 表面拒绝,反手上演一手实战示例. 内容: ① 一对多关系数据 (合并单元格)数据的 导出 ②一对多 ...

最新文章

  1. linux对文件的描述,对Linux文件系统的简单理解
  2. 为什么Redis内存不宜过大
  3. python类型转换、数值操作
  4. java中单例设计模式登记式单例类_java23种设计模式-创建型模式之单例模式
  5. java递增_java-8 – 如何按组递增
  6. mysql 表引擎 entity framework_EntityFramework之数据库以及表基本创建(一)
  7. 快速创建一个 spring mvc 示例
  8. alsa的动态库安装在哪里_源码编译安装MySQL8.0.20
  9. 冰点下载器手机版apk_冰点下载器官网
  10. linux 下bt远程下载,在Linux服务器上配置Transmission来离线下载BT种子
  11. linux识别罗兰声卡,罗兰UA22 USB音频接口声卡调试介绍篇
  12. PackageManager
  13. DAC904硬件电路
  14. chart的简单使用
  15. 塞尔维亚失联的成都女子与父亲相见!这期间发生了什么?
  16. 陪伴是最长情的告白,民生保险“链”接万家告白征集
  17. mysql 查询总数时条件_SQL查询数据库中符合条件的记录的总数
  18. 记录洛谷冰雹猜想的实现过程
  19. 从听不见声音到听见声音,零散记录自己的经历
  20. 服务器维护王者荣耀s22,王者荣耀S22新赛季,那些超实用的局外设置,你会用了吗?...

热门文章

  1. Web服务器压力测试工具?
  2. 调整linux字体渲染,开始使用 Manjaro(添加源+字体渲染去模糊+软件安装+优化配置+常见错误)(30)...
  3. jj斗地主服务器维护几点能好使啊,JJ斗地主比赛常见问题
  4. 怎么一键重装系统?装机大师一键重装图文教程
  5. C语言编程题:简单的a+b
  6. 英语在线听力翻译器_英语听力翻译软件下载_英语听力翻译2020官网下载地址_开心技术乐园...
  7. 计算机教室的教师端,极域电子教室教师端使用.doc
  8. Cisco Packet Tracer Student思科命令
  9. 计算机的电子报表模板,Excel记账本
  10. 黑马程序员全套Java教程_Java基础教程_API(十四)