Vue下载excel,easyExcel
1、在js里面增加导出方法
例如,在@/api/demo/index.js
/**** @param url 目标下载接口* @param query 查询参数* @param fileName 文件名称* @returns {*}*/
export function downBlobFile(url, query, fileName) {return request({url: url,method: "get",responseType: "blob",params: query}).then(response => {// 处理返回的文件流const blob = response.data;if (blob && blob.size === 0) {this.$notify.error("内容为空,无法下载");return;}const link = document.createElement("a");
//方法一//link.href = window.URL.createObjectURL(blob);
//方法二const binaryData = []binaryData.push(blob)link.href = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream;chartset=UTF-8' }))link.download = fileName;document.body.appendChild(link);link.click();window.setTimeout(function() {window.URL.revokeObjectURL(blob);document.body.removeChild(link);}, 0);});
}
2、main.js
import { downBlobFile } from './api/demo/index'
Vue.prototype.downBlobFile = downBlobFile
3、使用
this.downBlobFile('/url', this.searchForm, 'xxx.xlsx')
参数1:后台接口
参数2:查询条件
参数3:导出后文件名称
4、扩展java后端
1)、后台接口可以直接返回list数组
2)、后台可以使用easypoi
<!-- easypoi导入导出excel --> <dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>4.1.0</version> </dependency> <dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-web</artifactId><version>4.1.0</version> </dependency> <dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-annotation</artifactId><version>4.1.0</version> </dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.0.5</version> </dependency>
新建 ExcelUtils
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.itl.iap.common.base.dto.MesFilesVO;
import com.itl.iap.common.base.exception.CommonException;
import com.itl.iap.common.base.exception.CommonExceptionDefinition;
import com.itl.iap.common.base.model.FastDFSFile;
import com.itl.iap.common.base.response.ResponseData;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;public class ExcelUtils {public ExcelUtils() {}public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws CommonException {ExportParams exportParams = new ExportParams(title, sheetName);exportParams.setCreateHeadRows(isCreateHeader);defaultExport(list, pojoClass, fileName, response, exportParams);}public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws CommonException {defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));}public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws CommonException {defaultExport(list, fileName, response);}private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws CommonException {Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);if (workbook != null) {downLoadExcel(fileName, response, workbook);}}private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws CommonException {try {response.setCharacterEncoding("UTF-8");response.setHeader("content-Type", "application/vnd.ms-excel");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));workbook.write(response.getOutputStream());} catch (IOException var4) {throw new CommonException(var4.getMessage(), CommonExceptionDefinition.EXCEI_EXCEPTION);}}private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws CommonException {Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);if (workbook != null) {downLoadExcel(fileName, response, workbook);}}public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws CommonException {if (StrUtil.isBlank(filePath)) {return null;} else {ImportParams params = new ImportParams();params.setTitleRows(titleRows);params.setHeadRows(headerRows);List list = null;try {list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);return list;} catch (NoSuchElementException var7) {throw new CommonException("模板不能为空", CommonExceptionDefinition.EXCEI_EXCEPTION);} catch (Exception var8) {throw new CommonException(var8.getCause().getMessage(), CommonExceptionDefinition.EXCEI_EXCEPTION);}}}public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws CommonException {if (file == null) {return null;} else {ImportParams params = new ImportParams();params.setTitleRows(titleRows);params.setHeadRows(headerRows);List list = null;try {list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);return list;} catch (NoSuchElementException var7) {throw new CommonException("excel文件不能为空", CommonExceptionDefinition.EXCEI_EXCEPTION);} catch (Exception var8) {throw new CommonException(var8.getCause().getMessage(), CommonExceptionDefinition.EXCEI_EXCEPTION);}}}public static <T> List<T> importExcel(MultipartFile file, Integer sheet, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws CommonException {if (file == null) {return null;} else {if (sheet == null) {sheet = 0;}ImportParams params = new ImportParams();params.setTitleRows(titleRows);params.setHeadRows(headerRows);params.setStartSheetIndex(sheet);List list = null;try {list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);return list;} catch (NoSuchElementException var8) {throw new CommonException("excel文件不能为空", CommonExceptionDefinition.VERIFY_EXCEPTION);} catch (Exception var9) {throw new CommonException(var9.getCause().getMessage(), CommonExceptionDefinition.VERIFY_EXCEPTION);}}}public static void exportExcelWithImg(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, Short height, HttpServletResponse response) throws CommonException {ExportParams exportParams = new ExportParams(title, sheetName);exportParams.setCreateHeadRows(isCreateHeader);exportParams.setHeight(height);defaultExport(list, pojoClass, fileName, response, exportParams);}public static <T> Map<String, Object> importExcel(InputStream inputStream, Class<T> pojoclass, ImportParams params, String failFilePath, Consumer<List<T>> consumer, Function<FastDFSFile, ResponseData<MesFilesVO>> func) {FileOutputStream fileOutputStream = null;ExcelImportResult<T> result = null;HashMap map = new HashMap(16);try {result = ExcelImportUtil.importExcelMore(inputStream, pojoclass, params);if (result.isVerfiyFail()) {Workbook failWorkbook = result.getFailWorkbook();String str = DateUtil.format(new Date(), "yyyy-MM-dd");String fileDirPath = failFilePath + str.split("-")[0] + "/" + str.split("-")[1] + "/" + str.split("-")[2] + "/";FileUtil.mkdir(fileDirPath);String fileName = UUID.randomUUID().toString();String filePath = fileDirPath + fileName + ".xls";fileOutputStream = new FileOutputStream(FileUtil.file(filePath));failWorkbook.write(fileOutputStream);map.put("failCount", result.getFailList().size());map.put("failFilePath", filePath);if (func != null && StrUtil.isNotBlank(filePath)) {FastDFSFile fastDFSFile = new FastDFSFile(fileName, FileUtil.readBytes(filePath), ".xls");ResponseData<MesFilesVO> apply = (ResponseData)func.apply(fastDFSFile);if (apply.isSuccess()) {MesFilesVO data = (MesFilesVO)apply.getData();map.put("failFilePath", data.getFilePath());}}}} catch (Exception var25) {var25.printStackTrace();} finally {if (fileOutputStream != null) {try {fileOutputStream.close();} catch (IOException var24) {var24.printStackTrace();}}}if (result != null && CollUtil.isNotEmpty(result.getList())) {consumer.accept(result.getList());map.put("successCount", result.getList().size());}return map;}
}
使用
public void export(Demo demo, HttpServletRequest request, HttpServletResponse response) {List<Demo > list= demoService.selectList(demo);ExcelUtils.exportExcel(list, "title", "sheetName", Demo .class, "xxxx.xls", true, response);}
Demo.java
将导出的字段加上注解
@Excel(name = "名称" ,orderNum = "1")private String name;
Vue下载excel,easyExcel相关推荐
- js vue 下载excel(.xls)文件
@[TOC](js vue 下载excel(.xls)文件) 先看下载下来的excel文件 1.首先,后端给到的是一个文件在服务器中的存储地址 D:\MaxSecFile\Export\Alarm_2 ...
- vue下载excel表格模板和导入excel表格数据
vue下载excel表格模板和导入excel表格数据 vue制作excel表格模板给前端下载 vue制作excel表格模板给前端下载 最近有个需求,需要导入excel表格,并且还需要制作模板给用户下载 ...
- Vue 下载 Excel 文件
Vue 下载 Excel 文件 Vue前端将List列表下载为Excel文件 安装依赖包 首先前端将List列表生成Excel文件需要下载几个依赖包. npm install -S file-save ...
- vue下载excel直接上代码
1.使用vue的el-button标签定义一个点击事件 <el-form-item> <el-button size="small" type="tex ...
- vue下载excel模板文件,excel读取
一.下载excel模板文件 <template><a-button type="primary" @click="downloadExcel" ...
- 关于Mock -- vue下载excel乱码(血的教训)
当时在同步代码到svn上时,运维的同事同步代码npm install,本地环境调试做代码review. 这时忽略了一点,他打开着mockServer,噩梦开始了. 一个下载Excel的数据流接口,下载 ...
- SpringBoot+Vue下载Excel文件流(No converter、Excel乱码)
目录 介绍 No converter Excel乱码 正确代码 后端代码 前端代码 方法1 方法2 方法3 介绍 后端使用SpringBoot.Mybatis Plus,前端使用Vue,进行Excel ...
- vue下载excel模板
一.错误示例 1.请求接口 export const downloadTemplateApi = () => {return request({url: '/file/downloadTempl ...
- vue下载excel文件的方法
通过url下载 用后端提供文件的地址,直接使用浏览器去下载 通过window.location.href = 文件路径下载 window.location.href = `${location.ori ...
最新文章
- PyTorch | (1)初识PyTorch
- Anroid基础建设之View,Window,Activity
- webpack项目中使用vue
- python怎么知道用哪个库使用-Python链接数据库,使用哪个库,怎么操作?
- C++程序设计语言编程风格演变史
- 【spring boot】启动类启动 错误: 找不到或无法加载主类 com.codingapi.tm.TxManagerApplication 的解决方案...
- [转载]MySQL事务隔离级别
- FLEX与JAVA不通讯错误与解决方法(转)
- Telnet介绍及其安装
- 物业小区管理系统源码
- Win7 安装.Net 4.7.2 失败
- (88)信号发生器实现方法?三角波、方波、锯齿波,正弦波
- 网络安全先进技术与应用发展系列报告 用户实体行为分析技术(UEBA)
- 【P04】运放全差分放大器实现单端与平衡的相互转换
- vue导出excel加一个进度条_使用vue导出excel文件
- sklearn代码11 1-熵
- redis如何清空缓存
- ajax讲解和入门实例
- Java判断一个数组是否有相同的元素
- 面食窗口的API设计之道
热门文章
- 基于Irrlicht引擎的3D游戏实例v0.7
- docker-compose用法
- 输入一行字符,分别统计出其中英文字母,空格,数字和其他字符的个数
- php批号管理,批号_序列号编码规则
- Error while executing: npm ERR! D:\Program Files\Git\cmd\git.EXE ls-remote -h -t git://github.com/ad
- pycharm代码快速格式化Ctrl + Alt + L快捷键
- 东盟与中日韩(10+3)中小企业人工智能产业论坛
- [焦点访谈]黄碟竟然出正版
- J - MUV LUV EXTRA
- 用R语言实现卡方检验