经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTML/CSS » CSS » 查看文章
vue+element导入导出excel
来源:cnblogs  作者:bugSource  时间:2021/4/6 9:34:01  对本文有异议

1. 业务场景

由前台导入Excel表格,获取批量数据。根据一个数组导出Excel表格。

2.1 引入工具库

  1. npm install -S file-saver xlsx
  2. npm install -D script-loader

2.2 引入JS文件(excel导出使用)

下载地址:https://github.com/xrkffgg/Ktools/tree/master/JS/002.Excel

将 Blob.js 和 Export2Excel.js 放入项目目录src的excel文件夹下

3.GitHub项目Demo地址

地址:https://github.com/Beingyo/vue-test-template/tree/main/src/page/excelOperation

示例:

4. Demo

  1. <template>
  2. <div style="width: 100%">
  3. <div style="width: 400px;height: 600px;background-color: #f2f2f2;margin: 0 auto">
  4. <el-upload
  5. class="upload-demo"
  6. action=""
  7. :on-change="handleChange"
  8. :show-file-list="false"
  9. accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
  10. :auto-upload="false">
  11. <el-button size="small" type="primary">点击上传</el-button>
  12. <div slot="tip" class="el-upload__tip">只 xlsx / xls 件</div>
  13. </el-upload>
  14. <br><br><br><br>
  15. <div>
  16. <el-button @click="outExe">导出excel表格</el-button>
  17. </div>
  18. </div>
  19. </div>
  20. </template>
  21. <script>
  22. // import Blob from '../excel/Blob.js'
  23. // import Export2Excel from '../excel/Export2Excel.js'
  24. export default {
  25. data () {
  26. return {
  27. fileTemp: null,
  28. outdata: [],
  29. excelData: [],
  30. dataList: [
  31. {id: 1, name: '小白', code: '1', mobile: '13440000000', mail: '12580@qq.com', deptNames: '养老部', reasult: '就不给你成功'},
  32. {id: 2, name: '小白', code: '', mobile: '13440000000', mail: '12580@qq.com', deptNames: '养老部', reasult: '没写编号'},
  33. {id: 3, name: '小白', code: '1', mobile: '', mail: '12580@qq.com', deptNames: '养老部', reasult: '正常数据'},
  34. {id: 4, name: '小白', code: '1', mobile: '13440000000', mail: '', deptNames: '养老部', reasult: '正常数据'}
  35. ], // 请求回来的data
  36. }
  37. },
  38. created () {
  39. },
  40. methods: {
  41. handleChange (file, fileList) {
  42. this.fileTemp = file.raw
  43. if (this.fileTemp) {
  44. if ((this.fileTemp.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (this.fileTemp.type === 'application/vnd.ms-excel')) {
  45. this.importfxx()
  46. } else {
  47. this.$message({
  48. type: 'error',
  49. message: '附件格式错误,请删除后重新上传!'
  50. })
  51. }
  52. } else {
  53. this.$message({
  54. type: 'warning',
  55. message: '请上传附件!'
  56. })
  57. }
  58. },
  59. // 导入开始
  60. importfxx () {
  61. let _this = this
  62. let inputDOM = this.$refs.inputer
  63. // 通过DOM取文件数据
  64. this.file = event.currentTarget.files[0]
  65. var rABS = false // 是否将文件读取为二进制字符串
  66. var f = this.file
  67. var reader = new FileReader()
  68. // if (!FileReader.prototype.readAsBinaryString) {
  69. FileReader.prototype.readAsBinaryString = function (f) {
  70. var binary = ''
  71. var rABS = false // 是否将文件读取为二进制字符串
  72. var pt = this
  73. var wb // 读取完成的数据
  74. var outdata
  75. var reader = new FileReader()
  76. reader.onload = function (e) {
  77. var bytes = new Uint8Array(reader.result)
  78. var length = bytes.byteLength
  79. for (var i = 0; i < length; i++) {
  80. binary += String.fromCharCode(bytes[i])
  81. }
  82. var XLSX = require('xlsx')
  83. if (rABS) {
  84. wb = XLSX.read(btoa(fixdata(binary)), { // 手动转化
  85. type: 'base64'
  86. })
  87. } else {
  88. wb = XLSX.read(binary, {
  89. type: 'binary'
  90. })
  91. }
  92. const sheet2JSONOpts = {
  93. range: 1, // 第一行开始(A2),默认为第0行
  94. defval: ''// 给defval赋值为空的字符串
  95. }
  96. outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], sheet2JSONOpts)// outdata就是你想要的东西
  97. this.outdata = [...outdata]
  98. let arr = []
  99. this.outdata.map(v => {
  100. let obj = {}
  101. obj.name = v['姓名']
  102. obj.code = v['编号']
  103. obj.mobile = v['手机']
  104. obj.mail = v['邮箱']
  105. obj.deptNames = v['部门']
  106. arr.push(obj)
  107. })
  108. let para = {
  109. withList: arr
  110. }
  111. _this.$message({
  112. message: '请耐心等待导入成功',
  113. type: 'success'
  114. })
  115. if (para.withList.length > 100) {
  116. console.log('导入成员超过100名')
  117. } else {
  118. console.log('导入数据长度:' + para.withList.length)
  119. }
  120. console.log('导入数据:' + JSON.stringify(para))
  121. /* 发送请求 */
  122. // withImport(para).then(res => {
  123. // window.location.reload()
  124. // })
  125. }
  126. reader.readAsArrayBuffer(f)
  127. }
  128. if (rABS) {
  129. reader.readAsArrayBuffer(f)
  130. } else {
  131. reader.readAsBinaryString(f)
  132. }
  133. },
  134. // 导入结束
  135. // 导出开始
  136. outExe () {
  137. this.$confirm('此操作将导出excel文件, 是否继续?', '提示', {
  138. confirmButtonText: '确定',
  139. cancelButtonText: '取消',
  140. type: 'warning'
  141. }).then(() => {
  142. this.excelData = this.dataList // 你要导出的数据list。
  143. this.export2Excel()
  144. }).catch(() => {
  145. })
  146. },
  147. export2Excel () {
  148. var that = this
  149. require.ensure([], () => {
  150. // eslint-disable-next-line camelcase
  151. const { export_json_to_excel } = require('../excel/Export2Excel') // 这里必须使用绝对路径
  152. const tHeader = ['序号', '姓名', '编号', '手机', '邮箱', '部门', '失败原因'] // 导出的表头名
  153. const filterVal = ['id', 'name', 'code', 'mobile', 'mail', 'deptNames', 'reasult'] // 导出的表头字段名
  154. const list = that.excelData
  155. const data = that.formatJson(filterVal, list)
  156. console.log('导出数据:\n' + 'tHeader:' + tHeader + '\nxcelData:' + that.excelData)
  157. export_json_to_excel(tHeader, data, '导入模板')// 导出的表格名称,根据需要自己命名
  158. })
  159. },
  160. formatJson (filterVal, jsonData) {
  161. return jsonData.map(v => filterVal.map(j => v[j]))
  162. }
  163. // 导出结束
  164. }
  165. }
  166. </script>

5. 注意事项

sheet2JSONOpts是定义导出excel表格时数据的处理方式,详细使用看源码。

  1. export interface Sheet2JSONOpts extends DateNFOption {
  2. /** 输出格式 */
  3. header?: "A"|number|string[];
  4. /** 覆盖工作表范围 */
  5. range?: any;
  6. /** 在输出中包含或省略空白行 */
  7. blankrows?: boolean;
  8. /** 空值/未定义值的默认值 */
  9. defval?: any;
  10. /** 如果为true,则返回原始数据;如果为假,则返回格式化的文本 */
  11. raw?: boolean;
  12. /** 如果为true,则返回原始数字;如果为假,则返回格式化的数字 */
  13. rawNumbers?: boolean;
  14. }

6. 附加两个JS文件源码

Blob.js

  1. /* eslint-disable */
  2. /* Blob.js
  3. * A Blob implementation.
  4. * 2014-05-27
  5. *
  6. * By Eli Grey, http://eligrey.com
  7. * By Devin Samarin, https://github.com/eboyjr
  8. * License: X11/MIT
  9. * See LICENSE.md
  10. */
  11. /*global self, unescape */
  12. /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
  13. plusplus: true */
  14. /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
  15. const blob = function (view) {
  16. "use strict";
  17. view.URL = view.URL || view.webkitURL;
  18. if (view.Blob && view.URL) {
  19. try {
  20. new Blob;
  21. return;
  22. } catch (e) {}
  23. }
  24. // Internally we use a BlobBuilder implementation to base Blob off of
  25. // in order to support older browsers that only have BlobBuilder
  26. var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
  27. var
  28. get_class = function(object) {
  29. return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
  30. }
  31. , FakeBlobBuilder = function BlobBuilder() {
  32. this.data = [];
  33. }
  34. , FakeBlob = function Blob(data, type, encoding) {
  35. this.data = data;
  36. this.size = data.length;
  37. this.type = type;
  38. this.encoding = encoding;
  39. }
  40. , FBB_proto = FakeBlobBuilder.prototype
  41. , FB_proto = FakeBlob.prototype
  42. , FileReaderSync = view.FileReaderSync
  43. , FileException = function(type) {
  44. this.code = this[this.name = type];
  45. }
  46. , file_ex_codes = (
  47. "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
  48. + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
  49. ).split(" ")
  50. , file_ex_code = file_ex_codes.length
  51. , real_URL = view.URL || view.webkitURL || view
  52. , real_create_object_URL = real_URL.createObjectURL
  53. , real_revoke_object_URL = real_URL.revokeObjectURL
  54. , URL = real_URL
  55. , btoa = view.btoa
  56. , atob = view.atob
  57. , ArrayBuffer = view.ArrayBuffer
  58. , Uint8Array = view.Uint8Array
  59. ;
  60. FakeBlob.fake = FB_proto.fake = true;
  61. while (file_ex_code--) {
  62. FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
  63. }
  64. if (!real_URL.createObjectURL) {
  65. URL = view.URL = {};
  66. }
  67. URL.createObjectURL = function(blob) {
  68. var
  69. type = blob.type
  70. , data_URI_header
  71. ;
  72. if (type === null) {
  73. type = "application/octet-stream";
  74. }
  75. if (blob instanceof FakeBlob) {
  76. data_URI_header = "data:" + type;
  77. if (blob.encoding === "base64") {
  78. return data_URI_header + ";base64," + blob.data;
  79. } else if (blob.encoding === "URI") {
  80. return data_URI_header + "," + decodeURIComponent(blob.data);
  81. } if (btoa) {
  82. return data_URI_header + ";base64," + btoa(blob.data);
  83. } else {
  84. return data_URI_header + "," + encodeURIComponent(blob.data);
  85. }
  86. } else if (real_create_object_URL) {
  87. return real_create_object_URL.call(real_URL, blob);
  88. }
  89. };
  90. URL.revokeObjectURL = function(object_URL) {
  91. if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
  92. real_revoke_object_URL.call(real_URL, object_URL);
  93. }
  94. };
  95. FBB_proto.append = function(data/*, endings*/) {
  96. var bb = this.data;
  97. // decode data to a binary string
  98. if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
  99. var
  100. str = ""
  101. , buf = new Uint8Array(data)
  102. , i = 0
  103. , buf_len = buf.length
  104. ;
  105. for (; i < buf_len; i++) {
  106. str += String.fromCharCode(buf[i]);
  107. }
  108. bb.push(str);
  109. } else if (get_class(data) === "Blob" || get_class(data) === "File") {
  110. if (FileReaderSync) {
  111. var fr = new FileReaderSync;
  112. bb.push(fr.readAsBinaryString(data));
  113. } else {
  114. // async FileReader won't work as BlobBuilder is sync
  115. throw new FileException("NOT_READABLE_ERR");
  116. }
  117. } else if (data instanceof FakeBlob) {
  118. if (data.encoding === "base64" && atob) {
  119. bb.push(atob(data.data));
  120. } else if (data.encoding === "URI") {
  121. bb.push(decodeURIComponent(data.data));
  122. } else if (data.encoding === "raw") {
  123. bb.push(data.data);
  124. }
  125. } else {
  126. if (typeof data !== "string") {
  127. data += ""; // convert unsupported types to strings
  128. }
  129. // decode UTF-16 to binary string
  130. bb.push(unescape(encodeURIComponent(data)));
  131. }
  132. };
  133. FBB_proto.getBlob = function(type) {
  134. if (!arguments.length) {
  135. type = null;
  136. }
  137. return new FakeBlob(this.data.join(""), type, "raw");
  138. };
  139. FBB_proto.toString = function() {
  140. return "[object BlobBuilder]";
  141. };
  142. FB_proto.slice = function(start, end, type) {
  143. var args = arguments.length;
  144. if (args < 3) {
  145. type = null;
  146. }
  147. return new FakeBlob(
  148. this.data.slice(start, args > 1 ? end : this.data.length)
  149. , type
  150. , this.encoding
  151. );
  152. };
  153. FB_proto.toString = function() {
  154. return "[object Blob]";
  155. };
  156. FB_proto.close = function() {
  157. this.size = this.data.length = 0;
  158. };
  159. return FakeBlobBuilder;
  160. }(view));
  161. view.Blob = function Blob(blobParts, options) {
  162. var type = options ? (options.type || "") : "";
  163. var builder = new BlobBuilder();
  164. if (blobParts) {
  165. for (var i = 0, len = blobParts.length; i < len; i++) {
  166. builder.append(blobParts[i]);
  167. }
  168. }
  169. return builder.getBlob(type);
  170. };
  171. }
  172. exports.blob = blob;

Export2Excel.js

  1. /* eslint-disable */
  2. require('script-loader!file-saver');
  3. // require('script-loader!./Blob');
  4. const {blob} = require('./Blob')
  5. require('script-loader!xlsx/dist/xlsx.core.min');
  6. function generateArray(table) {
  7. var out = [];
  8. var rows = table.querySelectorAll('tr');
  9. var ranges = [];
  10. for (var R = 0; R < rows.length; ++R) {
  11. var outRow = [];
  12. var row = rows[R];
  13. var columns = row.querySelectorAll('td');
  14. for (var C = 0; C < columns.length; ++C) {
  15. var cell = columns[C];
  16. var colspan = cell.getAttribute('colspan');
  17. var rowspan = cell.getAttribute('rowspan');
  18. var cellValue = cell.innerText;
  19. if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;
  20. //Skip ranges
  21. ranges.forEach(function (range) {
  22. if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
  23. for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
  24. }
  25. });
  26. //Handle Row Span
  27. if (rowspan || colspan) {
  28. rowspan = rowspan || 1;
  29. colspan = colspan || 1;
  30. ranges.push({s: {r: R, c: outRow.length}, e: {r: R + rowspan - 1, c: outRow.length + colspan - 1}});
  31. }
  32. ;
  33. //Handle Value
  34. outRow.push(cellValue !== "" ? cellValue : null);
  35. //Handle Colspan
  36. if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
  37. }
  38. out.push(outRow);
  39. }
  40. return [out, ranges];
  41. };
  42. function datenum(v, date1904) {
  43. if (date1904) v += 1462;
  44. var epoch = Date.parse(v);
  45. return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
  46. }
  47. function sheet_from_array_of_arrays(data, opts) {
  48. var ws = {};
  49. var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
  50. for (var R = 0; R != data.length; ++R) {
  51. for (var C = 0; C != data[R].length; ++C) {
  52. if (range.s.r > R) range.s.r = R;
  53. if (range.s.c > C) range.s.c = C;
  54. if (range.e.r < R) range.e.r = R;
  55. if (range.e.c < C) range.e.c = C;
  56. var cell = {v: data[R][C]};
  57. if (cell.v == null) continue;
  58. var cell_ref = XLSX.utils.encode_cell({c: C, r: R});
  59. if (typeof cell.v === 'number') cell.t = 'n';
  60. else if (typeof cell.v === 'boolean') cell.t = 'b';
  61. else if (cell.v instanceof Date) {
  62. cell.t = 'n';
  63. cell.z = XLSX.SSF._table[14];
  64. cell.v = datenum(cell.v);
  65. }
  66. else cell.t = 's';
  67. ws[cell_ref] = cell;
  68. }
  69. }
  70. if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
  71. return ws;
  72. }
  73. function Workbook() {
  74. if (!(this instanceof Workbook)) return new Workbook();
  75. this.SheetNames = [];
  76. this.Sheets = {};
  77. }
  78. function s2ab(s) {
  79. var buf = new ArrayBuffer(s.length);
  80. var view = new Uint8Array(buf);
  81. for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  82. return buf;
  83. }
  84. export function export_table_to_excel(id) {
  85. var theTable = document.getElementById(id);
  86. console.log('a')
  87. var oo = generateArray(theTable);
  88. var ranges = oo[1];
  89. /* original data */
  90. var data = oo[0];
  91. var ws_name = "SheetJS";
  92. console.log(data);
  93. var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
  94. /* add ranges to worksheet */
  95. // ws['!cols'] = ['apple', 'banan'];
  96. ws['!merges'] = ranges;
  97. /* add worksheet to workbook */
  98. wb.SheetNames.push(ws_name);
  99. wb.Sheets[ws_name] = ws;
  100. var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
  101. saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), "test.xlsx")
  102. }
  103. function formatJson(jsonData) {
  104. console.log(jsonData)
  105. }
  106. export function export_json_to_excel(th, jsonData, defaultTitle) {
  107. /* original data */
  108. var data = jsonData;
  109. data.unshift(th);
  110. var ws_name = "SheetJS";
  111. var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
  112. /* add worksheet to workbook */
  113. wb.SheetNames.push(ws_name);
  114. wb.Sheets[ws_name] = ws;
  115. var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
  116. var title = defaultTitle || '列表'
  117. saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), title + ".xlsx")
  118. }

原文链接:http://www.cnblogs.com/bugSource/p/14582788.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号