【vue开发】vue导出Excel表格教程demo

前端工作量最多的就是需求,需求就是一直在变,比如当前端数据写完之后,需要用Excel把数据下载出来;再比如前端在没有数据库想写些demo玩时,也是很好的选择。

第一步安装依赖包,修改配置

1、装依赖:

  cnpm install  file-saver

  cnpm install xlsx

       cnpm install script-loader

2、修改配置:

在如下截图文件位置新增一行即可:'vendor': path.resolve(__dirname, '../src/vendor'),//新增加一行

 

 【提示】若新建的项目出现严格模式报错,修改如下文件,增加src/*

 

 

第二步在项目中创建一个新的文件夹用于存放Blob和Export2Excel两个js文件(需要把这个两个文件复制到自己的目录中)

 

 Export2Excel.js源码如下:

/* eslint-disable */
require('script-loader!file-saver');
// require('script-loader!src/vendor/Blob');
// require('script-loader!./Blob'); //这个本来有但是去掉功能暂无受影响
require('script-loader!xlsx/dist/xlsx.core.min');function generateArray(table) {var out = [];var rows = table.querySelectorAll('tr');var ranges = [];for (var R = 0; R < rows.length; ++R) {var outRow = [];var row = rows[R];var columns = row.querySelectorAll('td');for (var C = 0; C < columns.length; ++C) {var cell = columns[C];var colspan = cell.getAttribute('colspan');var rowspan = cell.getAttribute('rowspan');var cellValue = cell.innerText;if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;//Skip rangesranges.forEach(function (range) {if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);}});//Handle Row Spanif (rowspan || colspan) {rowspan = rowspan || 1;colspan = colspan || 1;ranges.push({s: {r: R, c: outRow.length}, e: {r: R + rowspan - 1, c: outRow.length + colspan - 1}});};//Handle ValueoutRow.push(cellValue !== "" ? cellValue : null);//Handle Colspanif (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);}out.push(outRow);}return [out, ranges];
};function datenum(v, date1904) {if (date1904) v += 1462;var epoch = Date.parse(v);return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}function sheet_from_array_of_arrays(data, opts) {var ws = {};var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};for (var R = 0; R != data.length; ++R) {for (var C = 0; C != data[R].length; ++C) {if (range.s.r > R) range.s.r = R;if (range.s.c > C) range.s.c = C;if (range.e.r < R) range.e.r = R;if (range.e.c < C) range.e.c = C;var cell = {v: data[R][C]};if (cell.v == null) continue;var cell_ref = XLSX.utils.encode_cell({c: C, r: R});if (typeof cell.v === 'number') cell.t = 'n';else if (typeof cell.v === 'boolean') cell.t = 'b';else if (cell.v instanceof Date) {cell.t = 'n';cell.z = XLSX.SSF._table[14];cell.v = datenum(cell.v);}else cell.t = 's';ws[cell_ref] = cell;}}if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);return ws;
}function Workbook() {if (!(this instanceof Workbook)) return new Workbook();this.SheetNames = [];this.Sheets = {};
}function s2ab(s) {var buf = new ArrayBuffer(s.length);var view = new Uint8Array(buf);for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;return buf;
}export function export_table_to_excel(id) {var theTable = document.getElementById(id);console.log('a')var oo = generateArray(theTable);var ranges = oo[1];/* original data */var data = oo[0];var ws_name = "SheetJS";console.log(data);var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);/* add ranges to worksheet */// ws['!cols'] = ['apple', 'banan'];ws['!merges'] = ranges;/* add worksheet to workbook */wb.SheetNames.push(ws_name);wb.Sheets[ws_name] = ws;var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), "test.xlsx")
}function formatJson(jsonData) {console.log(jsonData)
}export function export_json_to_excel(th, jsonData, defaultTitle) {/* original data */var data = jsonData;data.unshift(th);var ws_name = "SheetJS";var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);/* add worksheet to workbook */wb.SheetNames.push(ws_name);wb.Sheets[ws_name] = ws;var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});var title = defaultTitle || '列表'saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), title + ".xlsx")
}

Blob.js源码如下:

/* eslint-disable */
/* Blob.js*//*global self, unescape */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,plusplus: true *//*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */(function (view) {"use strict";view.URL = view.URL || view.webkitURL;if (view.Blob && view.URL) {try {new Blob;return;} catch (e) {}}// Internally we use a BlobBuilder implementation to base Blob off of// in order to support older browsers that only have BlobBuildervar BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function (view) {varget_class = function (object) {return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];}, FakeBlobBuilder = function BlobBuilder() {this.data = [];}, FakeBlob = function Blob(data, type, encoding) {this.data = data;this.size = data.length;this.type = type;this.encoding = encoding;}, FBB_proto = FakeBlobBuilder.prototype, FB_proto = FakeBlob.prototype, FileReaderSync = view.FileReaderSync, FileException = function (type) {this.code = this[this.name = type];}, file_ex_codes = ("NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "+ "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR").split(" "), file_ex_code = file_ex_codes.length, real_URL = view.URL || view.webkitURL || view, real_create_object_URL = real_URL.createObjectURL, real_revoke_object_URL = real_URL.revokeObjectURL, URL = real_URL, btoa = view.btoa, atob = view.atob, ArrayBuffer = view.ArrayBuffer, Uint8Array = view.Uint8Array, origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/;FakeBlob.fake = FB_proto.fake = true;while (file_ex_code--) {FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;}// Polyfill URLif (!real_URL.createObjectURL) {URL = view.URL = function (uri) {varuri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a"), uri_origin;uri_info.href = uri;if (!("origin" in uri_info)) {if (uri_info.protocol.toLowerCase() === "data:") {uri_info.origin = null;} else {uri_origin = uri.match(origin);uri_info.origin = uri_origin && uri_origin[1];}}return uri_info;};}URL.createObjectURL = function (blob) {vartype = blob.type, data_URI_header;if (type === null) {type = "application/octet-stream";}if (blob instanceof FakeBlob) {data_URI_header = "data:" + type;if (blob.encoding === "base64") {return data_URI_header + ";base64," + blob.data;} else if (blob.encoding === "URI") {return data_URI_header + "," + decodeURIComponent(blob.data);}if (btoa) {return data_URI_header + ";base64," + btoa(blob.data);} else {return data_URI_header + "," + encodeURIComponent(blob.data);}} else if (real_create_object_URL) {return real_create_object_URL.call(real_URL, blob);}};URL.revokeObjectURL = function (object_URL) {if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {real_revoke_object_URL.call(real_URL, object_URL);}};FBB_proto.append = function (data/*, endings*/) {var bb = this.data;// decode data to a binary stringif (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {varstr = "", buf = new Uint8Array(data), i = 0, buf_len = buf.length;for (; i < buf_len; i++) {str += String.fromCharCode(buf[i]);}bb.push(str);} else if (get_class(data) === "Blob" || get_class(data) === "File") {if (FileReaderSync) {var fr = new FileReaderSync;bb.push(fr.readAsBinaryString(data));} else {// async FileReader won't work as BlobBuilder is syncthrow new FileException("NOT_READABLE_ERR");}} else if (data instanceof FakeBlob) {if (data.encoding === "base64" && atob) {bb.push(atob(data.data));} else if (data.encoding === "URI") {bb.push(decodeURIComponent(data.data));} else if (data.encoding === "raw") {bb.push(data.data);}} else {if (typeof data !== "string") {data += ""; // convert unsupported types to strings
        }// decode UTF-16 to binary string
        bb.push(unescape(encodeURIComponent(data)));}};FBB_proto.getBlob = function (type) {if (!arguments.length) {type = null;}return new FakeBlob(this.data.join(""), type, "raw");};FBB_proto.toString = function () {return "[object BlobBuilder]";};FB_proto.slice = function (start, end, type) {var args = arguments.length;if (args < 3) {type = null;}return new FakeBlob(this.data.slice(start, args > 1 ? end : this.data.length), type, this.encoding);};FB_proto.toString = function () {return "[object Blob]";};FB_proto.close = function () {this.size = 0;delete this.data;};return FakeBlobBuilder;}(view));view.Blob = function (blobParts, options) {var type = options ? (options.type || "") : "";var builder = new BlobBuilder();if (blobParts) {for (var i = 0, len = blobParts.length; i < len; i++) {if (Uint8Array && blobParts[i] instanceof Uint8Array) {builder.append(blobParts[i].buffer);}else {builder.append(blobParts[i]);}}}var blob = builder.getBlob(type);if (!blob.slice && blob.webkitSlice) {blob.slice = blob.webkitSlice;}return blob;};var getPrototypeOf = Object.getPrototypeOf || function (object) {return object.__proto__;};view.Blob.prototype = getPrototypeOf(new view.Blob());
}(typeof self !== "undefined" && self|| typeof window !== "undefined" && window|| this
));

第三步在你组件中使用

tHeader:标题

filterVal:字段名

tableData:前端请求的数据

我写的demo组件源码如下:

<template><!-- 这是导出Excel的demo --><div class="hello "><van-field v-model="info.username" label="用户" placeholder="请输入用户名" /><van-field v-model="info.sex" label="性别" placeholder="请输入性别" /><van-field v-model="info.age" label="年龄" placeholder="请输入年龄" /><van-field v-model="info.phone" label="手机" placeholder="请输入手机号" /><van-field v-model="info.city" label="城市" placeholder="请输入城市" /><van-button class="margin-top" type="primary" @click="exportTo()">继续添加</van-button><van-button class="margin-left" type="primary" @click="exportToExcel()">导出表格</van-button><div class="text-left mid-auto margin-top"><div v-for="item in intData">{{item.username}}-{{item.sex}}-{{item.age}}-{{item.phone}}-{{item.city}}</br></div></div></div>
</template><script>import Vue from 'vue';import {Button,Field} from 'vant';import 'vant/lib/index.css';Vue.use(Button);Vue.use(Field);export default {name: 'HelloWorld',data() {return {info: {username: '',phone: '',city: "",sex: "",age: "",},tableData: [],intData: [],}},methods: {exportTo() {//push数据 接触双向绑定this.intData.push(JSON.parse(JSON.stringify(this.info)));this.tableData = this.intData;console.log(this.tableData)// let {username,phone,city,sex,age} = this.info;//表单置空继续输入this.info.username = "";this.info.phone = "";this.info.city = "";this.info.sex = "";this.info.age = "";},exportToExcel() {console.log('提交了', this.tableData)//excel数据导出require.ensure([], () => {const {export_json_to_excel} = require('../vendor/Export2Excel');const tHeader = ['用户名', '性别', '年龄', '手机号', '城市', ];const filterVal = ['username', 'sex', 'age', 'phone', 'city'];const list = this.tableData;const data = this.formatJson(filterVal, list);export_json_to_excel(tHeader, data, '列表excel');})},formatJson(filterVal, jsonData) {return jsonData.map(v => filterVal.map(j => v[j]))}}}
</script><!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>h1,h2 {font-weight: normal;}ul {list-style-type: none;padding: 0;}li {display: inline-block;margin: 0 10px;}a {color: #42b983;}.text-left {text-align: left;}.mid-auto {width: 86%;margin: auto;}.margin-top {margin-top: 20px;}.margin-left {margin-left: 20px;}
</style>

demo截图如下:

 导出的表格如下:

 

温馨提示:

      工作开发只是我们生存的一个技能,但是我们的生活不应该只是生存,如何把生活过得丰富有趣在这快节奏又圈子小的环境很难,要想好玩我们只能找平台,找圈子来结识志趣相投,有话题的人来调味生活,作者业余也是在努力活得有趣中,所以开了自己公众号,致力于将自己工作,兴趣,观点等结合,寻找和自己有话题的人,若有兴趣欢迎加入!!!

 

 

转载于:https://www.cnblogs.com/xiaohuizhang/p/11463509.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/423495.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

git学习(10):Git的使用--如何将本地项目上传到Github(两种简单、方便的方法)

将本地项目上传到Github&#xff08;两种简单、方便的方法&#xff09; 一、第一种方法&#xff1a; 首先你需要一个github账号&#xff0c;所有还没有的话先去注册吧&#xff01; https://github.com/ 我们使用git需要先安装git工具&#xff0c;这里给出下载地址&#xff0…

.NET中栈和堆的比较1

原文出处&#xff1a; http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx 尽管在.NET framework下我们并不需要担心内存管理和垃圾回收(Garbage Collection)&#xff0c;但是我们还是应该了解它们&#xff0c;以优化我们的…

前端学习(1):HTML和CSS导学

最近为什么捡起前端&#xff0c;主要工作太忙&#xff0c;有时间就会抓一下后端&#xff0c;前端是我以前啃得比较多的 再来一次呢&#xff0c;工作在忙也不能停止学习勒 第一部分 第二部分 第三部分 第四部分 如何学习

Spring Boot----Dubbo原理分析

环境&#xff1a;需要创建一个dubbo.xml 通过ImportResource()导入xml&#xff1a; 1、首先spring启动解析配置文件的每一个标签的总接口是 org.springframework.beans.factory.xml.BeanDefinitionParser 2、DubboBeanDefinitionParser是它的一个实现类&#xff0c;通过调用par…

前端学习(2):什么是html和css

什么是HTML&#xff1f; W3C&#xff1a;万维网联盟&#xff0c;是目前web技术领域最具权威和影响力的标准机构&#xff0c;目前为止&#xff0c;W3C已发布了200多项影响深远的web技术标准及实施指南。 Hypertext markup language:超文本标记语言&#xff0c;该语言书写的代码通…

基于小程序·云开发构建高考查分小程序丨实战

2019高考报名人数达到了 1031 万的新高&#xff0c;作为一名三年前参考高考的准程序猿&#xff0c;赶在高考前&#xff0c;加班加点从零开始做了一款高考查分小程序&#xff0c;算是一名老学长送给学弟学妹们的高考礼。上线仅 1 个月&#xff0c;用户数就突破了 1k&#xff0c;…

前端学习(3):vs code编辑器

下载地址 https://code.visualstudio.com 下载安装教程 变成中文 在编辑器中运行我们的网页 open in browser view in browser 选中文件----首选项----设置 常用快捷键

QuickPart应用系列

在上一篇解决方案包部署与收回篇章中&#xff0c;我只是稍微提了下QuickPart.也许刚接触这块内容的朋友&#xff0c;可能还不是很清楚&#xff0c;QuickPart具体的功能能实现什么。首先要告诉你的是QuickPart的人性化之处&#xff0c;那就是给开发人员开发webpart提供更简洁的方…

前端学习(4):chome浏览器

一、认识浏览器 浏览器是网页显示、运行的平台&#xff0c;常用的浏览器有IE、火狐&#xff08;Firefox&#xff09;、谷歌&#xff08;Chrome&#xff09;、Safari和Opera等。我们平时称为五大浏览器。IE最新版为Edge。 常用浏览器 二、浏览器市场份额 可以通过百度的统计网…

实战 IE8 开发人员工具

今天整理我收藏的漫画的时候发现 风云3 少了两集&#xff08;486、487&#xff09;&#xff0c;这对于收藏者来说基本是不可忍受的&#xff1b; 从风云一到三&#xff0c;应该一集也不能少的&#xff1b; 决定上网去找找&#xff0c;不过溜达一圈常去的分享论坛&#xff0c;由于…

前端学习(6):javascript简介

我们需要思考以下六个问题&#xff1a; 1、javaScript是什么&#xff1f; 2、javaScript的用途是什么&#xff1f; 3、javaScript和ECMAScript的关系是什么&#xff1f; 4、javaScript由哪几部分组成&#xff1f; 5、javaScript的执行原理是怎样的&#xff1f; 6、在页面…

前端学习(7):web的三大技术

HTML(5) 是一门标记型语言&#xff0c;主要由一些具备特殊含义的标签构成&#xff08;建筑物结构&#xff09; 所谓HTML是“超文本标记语言”的英文缩写。我们上网所看到网页&#xff0c;多数都是由HTML写成的。“超文本”是指页面内可以包含图片、链接&#xff0c;甚至音乐、…

scala的foreach和for

一句印象深刻的话&#xff0c;Alan Kay&#xff08;Smalltalk发明者&#xff09;说得一句话&#xff1a;“I’m not against types, but I dont know of any typesystems that arent a complete pain, so I still like dynamic typing”。 并不是静态类型不好&#xff0c;只是静…

前端学习(8):HTML的基本属性和结构

一、HTML文档结构 <!DOCTYPE html> <html lang"zh-CN"> <head> <meta charset"UTF-8"> <title>css样式优先级</title> </head> <body> </body> </html> <!DOCTYPE html>声明为HTML5文…

借助云开发轻松实现后台数据批量导出丨实战

小程序导出数据到excel表&#xff0c;借助云开发后台实现excel数据的保存 我们在开发小程序的过程中&#xff0c;可能会有这样的需求&#xff1a;如何将云数据库里的数据批量导出到excel表里&#xff1f; 这个需求可以用强大的云开发轻松实现&#xff01; 这里需要用到云函数&a…

Storm的ack机制在项目应用中的坑

正在学习storm的大兄弟们&#xff0c;我又来传道授业解惑了&#xff0c;是不是觉得自己会用ack了。好吧&#xff0c;那就让我开始啪啪打你们脸吧。 先说一下ACK机制&#xff1a; 为了保证数据能正确的被处理, 对于spout产生的每一个tuple, storm都会进行跟踪。 这里面涉及到ac…

云开发数据库VS传统数据库丨云开发101

云开发数据库与传统数据库的不同 在小程序云开发中&#xff0c;最核心的便是三大组件&#xff1a;数据库、云存储和云函数&#xff0c;从今天开始&#xff0c;我们将开始隔日更的专栏文章&#xff0c;云开发101&#xff0c;在第一周&#xff0c;我们将从最最核心的数据库开始说…

前端学习(10):HTML语义化

我理解的HTML语义化 经过查看别人博文中的一些描述&#xff0c;我将HTML的语义化总结为&#xff1a; 用最恰当的标签来标记内容。 该如何理解呢&#xff1f;比如需要加入一个标题&#xff0c;这个标题的字体比正文的要大写&#xff0c;还要加粗。能够实现这种效果的方法有很多…

博客中gitalk最新评论的获取 github api使用

博客中&#xff0c;对于网友的评论以及每篇文章的评论数还是很重要的。但是基于静态的页面想要存储动态的评论数据是比较难的&#xff0c;一般博客主题中都内置了评论插件&#xff0c;但是博客主题中对于最新评论的支持显示还是很少的&#xff0c;至少目前我是没怎么发现。博客…

前端学习(11):标题和段落

<!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>标题和段落</title> </head> <body><h1>我是歌谣</h1><h2>我是歌谣</h2><h3>我是歌谣</h3>&l…