Vue 纯前端导出Excel

一、下载依赖
npm install xlsx file-saver -S

npm install script-loader -S -D

二、.在 -src文件夹下创建增加两个文件
在这里插入图片描述

/* Blob.js
 * A Blob, File, FileReader & URL implementation.
 * 2019-04-19
 *
 * By Eli Grey, http://eligrey.com
 * By Jimmy Wärting, https://github.com/jimmywarting
 * License: MIT
 *   See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md
 */

;(function () {
    var global = typeof window === 'object'
        ? window : typeof self === 'object'
        ? self : this
  
    var BlobBuilder = global.BlobBuilder
      || global.WebKitBlobBuilder
      || global.MSBlobBuilder
      || global.MozBlobBuilder
  
    global.URL = global.URL || global.webkitURL || function (href, a) {
        a = document.createElement('a')
        a.href = href
        return a
    }
  
    var origBlob = global.Blob
    var createObjectURL = URL.createObjectURL
    var revokeObjectURL = URL.revokeObjectURL
    var strTag = global.Symbol && global.Symbol.toStringTag
    var blobSupported = false
    var blobSupportsArrayBufferView = false
    var arrayBufferSupported = !!global.ArrayBuffer
    var blobBuilderSupported = BlobBuilder
      && BlobBuilder.prototype.append
      && BlobBuilder.prototype.getBlob
  
    try {
      // Check if Blob constructor is supported
      blobSupported = new Blob(['ä']).size === 2
  
      // Check if Blob constructor supports ArrayBufferViews
      // Fails in Safari 6, so we need to map to ArrayBuffers there.
      blobSupportsArrayBufferView = new Blob([new Uint8Array([1, 2])]).size === 2
    } catch (e) {}
  
    /**
     * Helper function that maps ArrayBufferViews to ArrayBuffers
     * Used by BlobBuilder constructor and old browsers that didn't
     * support it in the Blob constructor.
     */
    function mapArrayBufferViews (ary) {
      return ary.map(function (chunk) {
        if (chunk.buffer instanceof ArrayBuffer) {
          var buf = chunk.buffer
  
          // if this is a subarray, make a copy so we only
          // include the subarray region from the underlying buffer
          if (chunk.byteLength !== buf.byteLength) {
            var copy = new Uint8Array(chunk.byteLength)
            copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength))
            buf = copy.buffer
          }
  
          return buf
        }
  
        return chunk
      })
    }
  
    function BlobBuilderConstructor (ary, options) {
      options = options || {}
  
      var bb = new BlobBuilder()
      mapArrayBufferViews(ary).forEach(function (part) {
        bb.append(part)
      })
  
      return options.type ? bb.getBlob(options.type) : bb.getBlob()
    }
  
    function BlobConstructor (ary, options) {
      return new origBlob(mapArrayBufferViews(ary), options || {})
    }
  
    if (global.Blob) {
      BlobBuilderConstructor.prototype = Blob.prototype
      BlobConstructor.prototype = Blob.prototype
    }
  
  
  
    /********************************************************/
    /*               String Encoder fallback                */
    /********************************************************/
    function stringEncode (string) {
      var pos = 0
      var len = string.length
      var Arr = global.Uint8Array || Array // Use byte array when possible
  
      var at = 0  // output position
      var tlen = Math.max(32, len + (len >> 1) + 7)  // 1.5x size
      var target = new Arr((tlen >> 3) << 3)  // ... but at 8 byte offset
  
      while (pos < len) {
        var value = string.charCodeAt(pos++)
        if (value >= 0xd800 && value <= 0xdbff) {
          // high surrogate
          if (pos < len) {
            var extra = string.charCodeAt(pos)
            if ((extra & 0xfc00) === 0xdc00) {
              ++pos
              value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000
            }
          }
          if (value >= 0xd800 && value <= 0xdbff) {
            continue  // drop lone surrogate
          }
        }
  
        // expand the buffer if we couldn't write 4 bytes
        if (at + 4 > target.length) {
          tlen += 8  // minimum extra
          tlen *= (1.0 + (pos / string.length) * 2)  // take 2x the remaining
          tlen = (tlen >> 3) << 3  // 8 byte offset
  
          var update = new Uint8Array(tlen)
          update.set(target)
          target = update
        }
  
        if ((value & 0xffffff80) === 0) {  // 1-byte
          target[at++] = value  // ASCII
          continue
        } else if ((value & 0xfffff800) === 0) {  // 2-byte
          target[at++] = ((value >> 6) & 0x1f) | 0xc0
        } else if ((value & 0xffff0000) === 0) {  // 3-byte
          target[at++] = ((value >> 12) & 0x0f) | 0xe0
          target[at++] = ((value >> 6) & 0x3f) | 0x80
        } else if ((value & 0xffe00000) === 0) {  // 4-byte
          target[at++] = ((value >> 18) & 0x07) | 0xf0
          target[at++] = ((value >> 12) & 0x3f) | 0x80
          target[at++] = ((value >> 6) & 0x3f) | 0x80
        } else {
          // FIXME: do we care
          continue
        }
  
        target[at++] = (value & 0x3f) | 0x80
      }
  
      return target.slice(0, at)
    }
  
    /********************************************************/
    /*               String Decoder fallback                */
    /********************************************************/
    function stringDecode (buf) {
      var end = buf.length
      var res = []
  
      var i = 0
      while (i < end) {
        var firstByte = buf[i]
        var codePoint = null
        var bytesPerSequence = (firstByte > 0xEF) ? 4
          : (firstByte > 0xDF) ? 3
            : (firstByte > 0xBF) ? 2
              : 1
  
        if (i + bytesPerSequence <= end) {
          var secondByte, thirdByte, fourthByte, tempCodePoint
  
          switch (bytesPerSequence) {
            case 1:
              if (firstByte < 0x80) {
                codePoint = firstByte
              }
              break
            case 2:
              secondByte = buf[i + 1]
              if ((secondByte & 0xC0) === 0x80) {
                tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
                if (tempCodePoint > 0x7F) {
                  codePoint = tempCodePoint
                }
              }
              break
            case 3:
              secondByte = buf[i + 1]
              thirdByte = buf[i + 2]
              if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
                tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
                if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
                  codePoint = tempCodePoint
                }
              }
              break
            case 4:
              secondByte = buf[i + 1]
              thirdByte = buf[i + 2]
              fourthByte = buf[i + 3]
              if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
                tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
                if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
                  codePoint = tempCodePoint
                }
              }
          }
        }
  
        if (codePoint === null) {
          // we did not generate a valid codePoint so insert a
          // replacement char (U+FFFD) and advance only 1 byte
          codePoint = 0xFFFD
          bytesPerSequence = 1
        } else if (codePoint > 0xFFFF) {
          // encode to utf16 (surrogate pair dance)
          codePoint -= 0x10000
          res.push(codePoint >>> 10 & 0x3FF | 0xD800)
          codePoint = 0xDC00 | codePoint & 0x3FF
        }
  
        res.push(codePoint)
        i += bytesPerSequence
      }
  
      var len = res.length
      var str = ''
      var i = 0
  
      while (i < len) {
        str += String.fromCharCode.apply(String, res.slice(i, i += 0x1000))
      }
  
      return str
    }
  
    // string -> buffer
    var textEncode = typeof TextEncoder === 'function'
      ? TextEncoder.prototype.encode.bind(new TextEncoder())
      : stringEncode
  
    // buffer -> string
    var textDecode = typeof TextDecoder === 'function'
      ? TextDecoder.prototype.decode.bind(new TextDecoder())
      : stringDecode
  
    function FakeBlobBuilder () {
      function isDataView (obj) {
        return obj && DataView.prototype.isPrototypeOf(obj)
      }
      function bufferClone (buf) {
        var view = new Array(buf.byteLength)
        var array = new Uint8Array(buf)
        var i = view.length
        while (i--) {
          view[i] = array[i]
        }
        return view
      }
      function array2base64 (input) {
        var byteToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  
        var output = []
  
        for (var i = 0; i < input.length; i += 3) {
          var byte1 = input[i]
          var haveByte2 = i + 1 < input.length
          var byte2 = haveByte2 ? input[i + 1] : 0
          var haveByte3 = i + 2 < input.length
          var byte3 = haveByte3 ? input[i + 2] : 0
  
          var outByte1 = byte1 >> 2
          var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4)
          var outByte3 = ((byte2 & 0x0F) << 2) | (byte3 >> 6)
          var outByte4 = byte3 & 0x3F
  
          if (!haveByte3) {
            outByte4 = 64
  
            if (!haveByte2) {
              outByte3 = 64
            }
          }
  
          output.push(
            byteToCharMap[outByte1], byteToCharMap[outByte2],
            byteToCharMap[outByte3], byteToCharMap[outByte4]
          )
        }
  
        return output.join('')
      }
  
      var create = Object.create || function (a) {
        function c () {}
        c.prototype = a
        return new c()
      }
  
      if (arrayBufferSupported) {
        var viewClasses = [
          '[object Int8Array]',
          '[object Uint8Array]',
          '[object Uint8ClampedArray]',
          '[object Int16Array]',
          '[object Uint16Array]',
          '[object Int32Array]',
          '[object Uint32Array]',
          '[object Float32Array]',
          '[object Float64Array]'
        ]
  
        var isArrayBufferView = ArrayBuffer.isView || function (obj) {
          return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
        }
      }
  
      function concatTypedarrays (chunks) {
        var size = 0
        var i = chunks.length
        while (i--) { size += chunks[i].length }
        var b = new Uint8Array(size)
        var offset = 0
        for (i = 0, l = chunks.length; i < l; i++) {
          var chunk = chunks[i]
          b.set(chunk, offset)
          offset += chunk.byteLength || chunk.length
        }
  
        return b
      }
  
      /********************************************************/
      /*                   Blob constructor                   */
      /********************************************************/
      function Blob (chunks, opts) {
        chunks = chunks || []
        opts = opts == null ? {} : opts
        for (var i = 0, len = chunks.length; i < len; i++) {
          var chunk = chunks[i]
          if (chunk instanceof Blob) {
            chunks[i] = chunk._buffer
          } else if (typeof chunk === 'string') {
            chunks[i] = textEncode(chunk)
          } else if (arrayBufferSupported && (ArrayBuffer.prototype.isPrototypeOf(chunk) || isArrayBufferView(chunk))) {
            chunks[i] = bufferClone(chunk)
          } else if (arrayBufferSupported && isDataView(chunk)) {
            chunks[i] = bufferClone(chunk.buffer)
          } else {
            chunks[i] = textEncode(String(chunk))
          }
        }
  
        this._buffer = global.Uint8Array
          ? concatTypedarrays(chunks)
          : [].concat.apply([], chunks)
        this.size = this._buffer.length
  
        this.type = opts.type || ''
        if (/[^\u0020-\u007E]/.test(this.type)) {
          this.type = ''
        } else {
          this.type = this.type.toLowerCase()
        }
      }
  
      Blob.prototype.arrayBuffer = function () {
        return Promise.resolve(this._buffer)
      }
  
      Blob.prototype.text = function () {
        return Promise.resolve(textDecode(this._buffer))
      }
  
      Blob.prototype.slice = function (start, end, type) {
        var slice = this._buffer.slice(start || 0, end || this._buffer.length)
        return new Blob([slice], {type: type})
      }
  
      Blob.prototype.toString = function () {
        return '[object Blob]'
      }
  
      /********************************************************/
      /*                   File constructor                   */
      /********************************************************/
      function File (chunks, name, opts) {
        opts = opts || {}
        var a = Blob.call(this, chunks, opts) || this
        a.name = name.replace(/\//g, ':')
        a.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date()
        a.lastModified = +a.lastModifiedDate
  
        return a
      }
  
      File.prototype = create(Blob.prototype)
      File.prototype.constructor = File
  
      if (Object.setPrototypeOf) {
        Object.setPrototypeOf(File, Blob)
      } else {
        try { File.__proto__ = Blob } catch (e) {}
      }
  
      File.prototype.toString = function () {
        return '[object File]'
      }
  
      /********************************************************/
      /*                FileReader constructor                */
      /********************************************************/
      function FileReader () {
          if (!(this instanceof FileReader)) {
          throw new TypeError("Failed to construct 'FileReader': Please use the 'new' operator, this DOM object constructor cannot be called as a function.")
        }
  
          var delegate = document.createDocumentFragment()
          this.addEventListener = delegate.addEventListener
          this.dispatchEvent = function (evt) {
              var local = this['on' + evt.type]
              if (typeof local === 'function') local(evt)
              delegate.dispatchEvent(evt)
          }
          this.removeEventListener = delegate.removeEventListener
      }
  
      function _read (fr, blob, kind) {
          if (!(blob instanceof Blob)) {
          throw new TypeError("Failed to execute '" + kind + "' on 'FileReader': parameter 1 is not of type 'Blob'.")
        }
  
          fr.result = ''
  
          setTimeout(function () {
              this.readyState = FileReader.LOADING
              fr.dispatchEvent(new Event('load'))
              fr.dispatchEvent(new Event('loadend'))
          })
      }
  
      FileReader.EMPTY = 0
      FileReader.LOADING = 1
      FileReader.DONE = 2
      FileReader.prototype.error = null
      FileReader.prototype.onabort = null
      FileReader.prototype.onerror = null
      FileReader.prototype.onload = null
      FileReader.prototype.onloadend = null
      FileReader.prototype.onloadstart = null
      FileReader.prototype.onprogress = null
  
      FileReader.prototype.readAsDataURL = function (blob) {
          _read(this, blob, 'readAsDataURL')
          this.result = 'data:' + blob.type + ';base64,' + array2base64(blob._buffer)
      }
  
      FileReader.prototype.readAsText = function (blob) {
          _read(this, blob, 'readAsText')
          this.result = textDecode(blob._buffer)
      }
  
      FileReader.prototype.readAsArrayBuffer = function (blob) {
        _read(this, blob, 'readAsText')
         // return ArrayBuffer when possible
        this.result = (blob._buffer.buffer || blob._buffer).slice()
      }
  
      FileReader.prototype.abort = function () {}
  
      /********************************************************/
      /*                         URL                          */
      /********************************************************/
      URL.createObjectURL = function (blob) {
        return blob instanceof Blob
          ? 'data:' + blob.type + ';base64,' + array2base64(blob._buffer)
          : createObjectURL.call(URL, blob)
      }
  
      URL.revokeObjectURL = function (url) {
        revokeObjectURL && revokeObjectURL.call(URL, url)
      }
  
      /********************************************************/
      /*                         XHR                          */
      /********************************************************/
      var _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send
      if (_send) {
        XMLHttpRequest.prototype.send = function (data) {
          if (data instanceof Blob) {
            this.setRequestHeader('Content-Type', data.type)
            _send.call(this, textDecode(data._buffer))
          } else {
            _send.call(this, data)
          }
        }
      }
  
      global.FileReader = FileReader
      global.File = File
      global.Blob = Blob
    }
  
    function fixFileAndXHR () {
      var isIE = !!global.ActiveXObject || (
        '-ms-scroll-limit' in document.documentElement.style &&
        '-ms-ime-align' in document.documentElement.style
      )
  
      // Monkey patched
      // IE don't set Content-Type header on XHR whose body is a typed Blob
      // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6047383
      var _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send
      if (isIE && _send) {
        XMLHttpRequest.prototype.send = function (data) {
          if (data instanceof Blob) {
            this.setRequestHeader('Content-Type', data.type)
            _send.call(this, data)
          } else {
            _send.call(this, data)
          }
        }
      }
  
      try {
        new File([], '')
      } catch (e) {
        try {
          var klass = new Function('class File extends Blob {' +
            'constructor(chunks, name, opts) {' +
              'opts = opts || {};' +
              'super(chunks, opts || {});' +
              'this.name = name.replace(/\//g, ":");' +
              'this.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date();' +
              'this.lastModified = +this.lastModifiedDate;' +
            '}};' +
            'return new File([], ""), File'
          )()
          global.File = klass
        } catch (e) {
          var klass = function (b, d, c) {
            var blob = new Blob(b, c)
            var t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date()
  
            blob.name = d.replace(/\//g, ':')
            blob.lastModifiedDate = t
            blob.lastModified = +t
            blob.toString = function () {
              return '[object File]'
            }
  
            if (strTag) {
              blob[strTag] = 'File'
            }
  
            return blob
          }
          global.File = klass
        }
      }
    }
  
    if (blobSupported) {
      fixFileAndXHR()
      global.Blob = blobSupportsArrayBufferView ? global.Blob : BlobConstructor
    } else if (blobBuilderSupported) {
      fixFileAndXHR()
      global.Blob = BlobBuilderConstructor
    } else {
      FakeBlobBuilder()
    }
  
    if (strTag) {
      File.prototype[strTag] = 'File'
      Blob.prototype[strTag] = 'Blob'
      FileReader.prototype[strTag] = 'FileReader'
    }
  
    var blob = global.Blob.prototype
    var stream
  
    function promisify(obj) {
      return new Promise(function(resolve, reject) {
        obj.onload =
        obj.onerror = function(evt) {
          obj.onload =
          obj.onerror = null
  
          evt.type === 'load'
            ? resolve(obj.result || obj)
            : reject(new Error('Failed to read the blob/file'))
        }
      })
    }
  
  
    try {
      new ReadableStream({ type: 'bytes' })
      stream = function stream() {
        var position = 0
        var blob = this
  
        return new ReadableStream({
          type: 'bytes',
          autoAllocateChunkSize: 524288,
  
          pull: function (controller) {
            var v = controller.byobRequest.view
            var chunk = blob.slice(position, position + v.byteLength)
            return chunk.arrayBuffer()
            .then(function (buffer) {
              var uint8array = new Uint8Array(buffer)
              var bytesRead = uint8array.byteLength
  
              position += bytesRead
              v.set(uint8array)
                controller.byobRequest.respond(bytesRead)
  
              if(position >= blob.size)
                controller.close()
            })
          }
        })
      }
    } catch (e) {
      try {
        new ReadableStream({})
        stream = function stream(blob){
          var position = 0
          var blob = this
  
          return new ReadableStream({
            pull: function (controller) {
              var chunk = blob.slice(position, position + 524288)
  
              return chunk.arrayBuffer().then(function (buffer) {
                position += buffer.byteLength
                var uint8array = new Uint8Array(buffer)
                controller.enqueue(uint8array)
  
                if (position == blob.size)
                  controller.close()
              })
            }
          })
        }
      } catch (e) {
        try {
          new Response('').body.getReader().read()
          stream = function stream() {
            return (new Response(this)).body
          }
        } catch (e) {
          stream = function stream() {
            throw new Error('Include https://github.com/MattiasBuelens/web-streams-polyfill')
          }
        }
      }
    }
  
  
    if (!blob.arrayBuffer) {
      blob.arrayBuffer = function arrayBuffer() {
        var fr = new FileReader()
        fr.readAsArrayBuffer(this)
        return promisify(fr)
      }
    }
  
    if (!blob.text) {
      blob.text = function text() {
        var fr = new FileReader()
        fr.readAsText(this)
        return promisify(fr)
      }
    }
  
    if (!blob.stream) {
      blob.stream = stream
    }
  })()
/* eslint-disable */
// Export2Excel.js
require('script-loader!file-saver');
require('./Blob.js');
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 ranges
            ranges.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 Span
            if (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 Value
            outRow.push(cellValue !== "" ? cellValue : null);

            //Handle Colspan
            if (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")
}
 methods: {
     handleDownload() {
        this.downloadLoading = true
        require.ensure([], () => {
          const { export_json_to_excel } = require('@/vendor/Export2Excel')
          const tHeader = ['日期', '姓名', '地址']
          const filterVal = ['date', 'name', 'address']
          const list = this.tableData
          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '列表excel')
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      }

  }

热门文章

暂无图片
编程学习 ·

C语言二分查找详解

二分查找是一种知名度很高的查找算法&#xff0c;在对有序数列进行查找时效率远高于传统的顺序查找。 下面这张动图对比了二者的效率差距。 二分查找的基本思想就是通过把目标数和当前数列的中间数进行比较&#xff0c;从而确定目标数是在中间数的左边还是右边&#xff0c;将查…
暂无图片
编程学习 ·

GMX 命令分类列表

建模和计算操作命令&#xff1a; 1.1 . 创建拓扑与坐标文件 gmx editconf - 编辑模拟盒子以及写入子组(subgroups) gmx protonate - 结构质子化 gmx x2top - 根据坐标生成原始拓扑文件 gmx solvate - 体系溶剂化 gmx insert-molecules - 将分子插入已有空位 gmx genconf - 增加…
暂无图片
编程学习 ·

一文高效回顾研究生课程《数值分析》重点

数值分析这门课的本质就是用离散的已知点去估计整体&#xff0c;就是由黑盒子产生的结果去估计这个黑盒子。在数学里这个黑盒子就是一个函数嘛&#xff0c;这门课会介绍许多方法去利用离散点最大化地逼近这个函数&#xff0c;甚至它的导数、积分&#xff0c;甚至微分方程的解。…
暂无图片
编程学习 ·

在职阿里5年,一个28岁女软测工程师的心声

简单的先说一下&#xff0c;坐标杭州&#xff0c;14届本科毕业&#xff0c;算上年前在阿里巴巴的面试&#xff0c;一共有面试了有6家公司&#xff08;因为不想请假&#xff0c;因此只是每个晚上去其他公司面试&#xff0c;所以面试的公司比较少&#xff09; ​ 编辑切换为居中…
暂无图片
编程学习 ·

字符串左旋c语言

目录 题目&#xff1a; 解题思路&#xff1a; 第一步&#xff1a; 第二步&#xff1a; 第三步&#xff1a; 总代码&#xff1a; 题目&#xff1a; 实现一个函数&#xff0c;可以左旋字符串中的k个字符。 例如&#xff1a; ABCD左旋一个字符得到BCDA ABCD左旋两个字符…
暂无图片
编程学习 ·

设计模式--观察者模式笔记

模式的定义与特点 观察者&#xff08;Observer&#xff09;模式的定义&#xff1a;指多个对象间存在一对多的依赖关系&#xff0c;当一个对象的状态发生改变时&#xff0c;所有依赖于它的对象都得到通知并被自动更新。这种模式有时又称作发布-订阅模式、模型-视图模式&#xf…
暂无图片
编程学习 ·

睡觉突然身体动不了,什么是睡眠痽痪症

很多朋友可能有这样的体验&#xff0c;睡觉过程中突然意识清醒&#xff0c;身体却动弹不了。这时候感觉非常恐怖&#xff0c;希望旁边有一个人推自己一下。阳光以前也经常会碰到这样的情况&#xff0c;一年有一百多次&#xff0c;那时候很害怕晚上到来&#xff0c;睡觉了就会出…
暂无图片
编程学习 ·

深入理解C++智能指针——浅析MSVC源码

文章目录unique_ptrshared_ptr 与 weak_ptrstd::bad_weak_ptr 异常std::enable_shared_from_thisunique_ptr unique_ptr 是一个只移型别&#xff08;move-only type&#xff0c;只移型别还有std::mutex等&#xff09;。 结合一下工厂模式&#xff0c;看看其基本用法&#xff…
暂无图片
编程学习 ·

@TableField(exist = false)

TableField(exist false) //申明此字段不在数据库存在&#xff0c;但代码中需要用到它&#xff0c;通知Mybatis-plus在做写库操作是忽略它。,.
暂无图片
编程学习 ·

Java Web day15

第十二章文件上传和下载 一、如何实现文件上传 要实现Web开发中的文件上传功能&#xff0c;通常需要完成两步操作&#xff1a;一.是在Web页面中添加上传输入项&#xff1b;二是在Servlet中读取上传文件的数据&#xff0c;并保存到本地硬盘中。 需要使用一个Apache组织提供一个…
暂无图片
编程学习 ·

【51nod 2478】【单调栈】【前缀和】小b接水

小b接水题目解题思路Code51nod 2478 小b接水 题目 输入样例 12 0 1 0 2 1 0 1 3 2 1 2 1输出样例 6解题思路 可以发现最后能拦住水的都是向两边递减高度&#xff08;&#xff1f;&#xff09; 不管两个高积木之间的的积木是怎样乱七八糟的高度&#xff0c;最后能用来装水的…
暂无图片
编程学习 ·

花了大半天写了一个UVC扩展单元调试工具

基于DIRECTSHOW 实现的&#xff0c;用的是MFC VS2019. 详见&#xff1a;http://www.usbzh.com/article/detail-761.html 获取方法 加QQ群:952873936&#xff0c;然后在群文件\USB调试工具&测试软件\UVCXU-V1.0(UVC扩展单元调试工具-USB中文网官方版).exe USB中文网 USB中文…
暂无图片
编程学习 ·

贪心(一):区间问题、Huffman树

区间问题 例题一&#xff1a;区间选点 给定 N 个闭区间 [ai,bi]请你在数轴上选择尽量少的点&#xff0c;使得每个区间内至少包含一个选出的点。 输出选择的点的最小数量。 位于区间端点上的点也算作区间内。 输入格式 第一行包含整数 N&#xff0c;表示区间数。 接下来 …
暂无图片
编程学习 ·

C语言练习实例——费氏数列

目录 题目 解法 输出结果 题目 Fibonacci为1200年代的欧洲数学家&#xff0c;在他的着作中曾经提到&#xff1a;「若有一只免子每个月生一只小免子&#xff0c;一个月后小免子也开始生产。起初只有一只免子&#xff0c;一个月后就有两只免子&#xff0c;二个月后有三只免子…
暂无图片
编程学习 ·

Android开发(2): Android 资源

个人笔记整理 Android 资源 Android中的资源&#xff0c;一般分为两类&#xff1a; 系统内置资源&#xff1a;Android SDK中所提供的已经定义好的资源&#xff0c;用户可以直接拿来使用。 用户自定义资源&#xff1a;用户自己定义或引入的&#xff0c;只适用于当前应用的资源…
暂无图片
编程学习 ·

零基础如何在短时间内拿到算法offer

​算法工程师是利用算法处理事物的职业 算法&#xff08;Algorithm&#xff09;是一系列解决问题的清晰指令&#xff0c;也就是说&#xff0c;能够对一定规范的输入&#xff0c;在有限时间内获得所要求的输出。 如果一个算法有缺陷&#xff0c;或不适合于某个问题&#xff0c;执…
暂无图片
编程学习 ·

人工智能:知识图谱实战总结

人工智能python&#xff0c;NLP&#xff0c;知识图谱&#xff0c;机器学习&#xff0c;深度学习人工智能&#xff1a;知识图谱实战前言一、实体建模工具Protegepython&#xff0c;NLP&#xff0c;知识图谱&#xff0c;机器学习&#xff0c;深度学习 人工智能&#xff1a;知识图…
暂无图片
编程学习 ·

【无标题】

这里写自定义目录标题欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题&#xff0c;有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注…