首页 > 其他分享 >vue导入excel表格

vue导入excel表格

时间:2023-11-27 14:56:49浏览次数:43  
标签:function vue URL type excel 导入 var data view

1.vue导入模版信息。进行数据操作

首先要安装  npm install file-saver   npm install xlsx   npm install script-loader,在src下面创建一个excel文件夹,查创建2个js(Blob.js,Export2Excel.js)

utils/vendor/Export2Excel.js文件

/* eslint-disable */
require('script-loader!file-saver');
require('script-loader!@/utils/vendor/Blob');//转二进制用  这边要写你的blob的实际地址
require('script-loader!xlsx/dist/xlsx.core.min');
// require('script-loader!xlsx-style');
import XLSX from "xlsx-style";
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);
  var oo = generateArray(theTable);
  var ranges = oo[1];

  /* original data */
  var data = oo[0];
  var ws_name = "SheetJS";

  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) {
}
export function export_json_to_excel(th, jsonData, defaultTitle,autoWidth) {

  /* original data */

  var data = jsonData;
  data.unshift(th);
  var ws_name = "SheetJS";

  var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
  if (autoWidth) {
    /*设置worksheet每列的最大宽度*/
    const colWidth = data.map(row =>
      row.map(val => {
        /*先判断是否为null/undefined*/
        if (val == null || val == undefined || val == "") {
          return {
            wch: 10
          };
        } else if (val.toString().charCodeAt(0) > 255) {
          /*再判断是否为中文*/
          return {
            wch: val.toString().length * 2
          };
        } else {
          return {
            wch: val.toString().length * 1.4
          };
        }
      })
    );
    let result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
      for (let j = 0; j < colWidth[i].length; j++) {
        if (result[j]["wch"] < colWidth[i][j]["wch"]) {
          result[j]["wch"] = colWidth[i][j]["wch"];
        }
      }
    }
    ws["!cols"] = result;
  }


  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;


  var dataInfo = wb.Sheets[wb.SheetNames[0]];
  // 设置单元格框线
  const borderAll = {
    top: {
      style: "thin"
    },
    bottom: {
      style: "thin"
    },
    left: {
      style: "thin"
    },
    right: {
      style: "thin"
    }
  };


// 标题行
  let arr = [
    "A1",
    "B1",
    "C1",
    "D1",
    "E1",
    "F1",
    "G1",
    "H1",
    "I1",
    "J1",
    "K1",
    "L1",
    "M1",
    "N1",
    "O1",
    "P1",
    "Q1",
    "R1",
    "S1",
    "T1",
    "U1",
    "V1",
    "W1",
    "X1",
    "Y1",
    "Z1",
    "AA1",
    "AB1",
    "AC1",
    "AD1",
    "AE1",
    "AF1",
    "AG1",
    "AH1",
    "AI1",
    "AJ1",
    "AK1",
    "AL1",
    "AM1",
    "AN1",
    "AO1",
    "AP1",
    "AQ1",
    "AR1",
    "AS1",
    "AT1",
    "AU1",
    "AV1",
    "AW1",
    "AX1",
    "AY1",
    "AZ1",
    "BA1",
    "BB1",
    "BC1",
    "BD1",
    "BE1",
    "BF1",
    "BG1",
    "BH1",
    "BI1",
    "BJ1",
    "BK1",
    "BL1",
    "BM1",
    "BN1",
    "BO1",
    "BP1",
    "BQ1",
    "BR1",
    "BS1",
    "BT1",
    "BU1",
    "BV1",
    "BW1",
    "BX1",
    "BY1",
    "BZ1",
  ];
  //设置主标题样式
  let style = {
    font: {
      // name: "宋体",
      // sz: 18,
      color: { rgb: "000000" },

      bold: true
      // italic: false,
      // underline: false
    },
    fill: {
      fgColor: {
        rgb: "999999"
      },
    },
    alignment: {
      horizontal: "center",
      vertical: "center"
    }
  }

  //excel标题样式
  for (var i = 0; i < th.length; i++) {
    dataInfo[arr[i]].s = style;
  }

  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")
}

utils/vendor/Blob.js文件

/* eslint-disable */
/* Blob.js
 * A Blob implementation.
 * 2014-05-27
 *
 * By Eli Grey, http://eligrey.com
 * By Devin Samarin, https://github.com/eboyjr
 * License: X11/MIT
 *   See LICENSE.md
 */

/*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 BlobBuilder
    var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
            var
                get_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
                ;
            FakeBlob.fake = FB_proto.fake = true;
            while (file_ex_code--) {
                FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
            }
            if (!real_URL.createObjectURL) {
                URL = view.URL = {};
            }
            URL.createObjectURL = function(blob) {
                var
                    type = 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 string
                if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
                    var
                        str = ""
                        , 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 sync
                        throw 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 = this.data.length = 0;
            };
            return FakeBlobBuilder;
        }(view));

    view.Blob = function Blob(blobParts, options) {
        var type = options ? (options.type || "") : "";
        var builder = new BlobBuilder();
        if (blobParts) {
            for (var i = 0, len = blobParts.length; i < len; i++) {
                builder.append(blobParts[i]);
            }
        }
        return builder.getBlob(type);
    };
}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this));

封装方法exportFile.js

//导出当前页,格式excel
export  function exportCurrent(tableColumn,data,fileName, timeFlag) {
  var heards = [];
  var column = [];
  tableColumn.map((item) => {
    if(item.label != '操作'){
      heards.push(item.label);//表头
      column.push(item.prop);//data key
    }
  })

  exportExcel(heards,column,data,fileName, timeFlag);
}


//导出当前页,格式csv
export  function exportCurrentCsv(tableColumn,data) {
  var heards = [];
  var column = [];
  tableColumn.map((item) => {
    if(item.label != '操作'){
      heards.push(item.label);//表头
      column.push(item.prop);//data key
    }
  })
  const exportData =  data.map((item) => {
    var data = {}
    for(let i =0;i<column.length;i++){
      let key = column[i];
      data[key] = item[key]
    }
    return Object.values(data);
  })
  exportCsv([
    heards,
    ...exportData,
  ]);
}
export function arrayToCsv(data, args = {}) {
      let columnDelimiter = args.columnDelimiter || ",";
      let lineDelimiter = args.lineDelimiter || "\n";
      return data.reduce((csv, row) => {
        const rowContent = Array.isArray(row)
          ? row.reduce((rowTemp, col) => {
              let ret = rowTemp ? rowTemp + columnDelimiter : rowTemp;
              if (col) {
                let formatedCol = col
                  .toString()
                  .replace(new RegExp(lineDelimiter, "g"), " ");
                ret += /,/.test(formatedCol)? `"${formatedCol}"` : formatedCol;
              }
              return ret;
            }, "")
          : row;
        return (csv ? csv + lineDelimiter : "") + rowContent;
      }, "");
    }
    const BOM = "\uFEFF";
    var timestamp = new Date().getTime()  // 生成时间戳
    export function exportCsv(inputData, filename = "file" + timestamp + ".csv") {  // 定义文件的名字
      const csv = arrayToCsv(inputData);
      if (navigator.msSaveOrOpenBlob) {
        let blob = new Blob([BOM + csv], { type: "text/csv;charset=utf-8;" });
        navigator.msSaveOrOpenBlob(blob, filename);
      } else {
        let uri = encodeURI(`data:text/csv;charset=utf-8,${BOM}${csv}`);
        let downloadLink = document.createElement("a");
        downloadLink.href = uri;
        downloadLink.download = filename;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      }
    }


export function exportExcel(tHeader,filterVal,list,fileName, timeFlag) {
  if(typeof (fileName) == 'undefined' || fileName == ''){
    fileName = "file" + getCurrentTime();
  }else {
    if (timeFlag !== false) {
      fileName += getCurrentTime();
    }
  }
  require.ensure([], () => {
    const { export_json_to_excel } = require('@/utils/vendor/Export2Excel');
    const data = list.map(v => filterVal.map(j => v[j]));
    export_json_to_excel(tHeader, data, fileName, true);
  })
}


function getCurrentTime () {
  let date = new Date()
  let Y = date.getFullYear()
  let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)
  let D = date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate()
  let hours = date.getHours()
  let minutes = date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes()
  let seconds = date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds()
  date = Y.toString() +  M.toString() +  D.toString() +  hours.toString() +  minutes.toString() +  seconds.toString();
  return date
}

导出文件

import { exportCurrent } from '@/utils/exportFile';
//导出
    handleExport() {
        var data = this.tableData;
        var tableColumn = this.tableColumn;
        exportCurrent(tableColumn, data, '注塑班长日报');
    },

注意:下载xlsx-style会提示报错

此时就需要打包补丁 用到插件patch-package

npm i patch-package --save-dev

yarn add patch-package --dev
修改node_modules文件后
cpt = require('./cpt' + 'able') 改为 cpt = cptable;

npx patch-package xlsx-style
执行过后会生成patches文件夹

参考内容有:
1、作者:Easter_D
链接:https://www.jianshu.com/p/bdcfe69a1a13

2、作者:无证程序员日志
链接:https://www.cnblogs.com/jydeng/p/14120348.html
3、若依框架

标签:function,vue,URL,type,excel,导入,var,data,view
From: https://www.cnblogs.com/axingya/p/17859355.html

相关文章

  • Vue-加入购物车-判断token添加登录提示
    Vue-加入购物车-判断token添加登录提示目标:给未登录的用户,添加登录提示说明:加入购物车,是一个登录后的用户才能进行的操作,所以需要进行鉴权判断,判断用户token是否存在若存在:继续加入购物车操作不存在:提示用户未登录,引导到登录页,登录完回跳addCart(){//判断token......
  • Vue中自定义组件监听事件传参
    自定义数字框组件如下<template><divclass="count-box"><button@click="handleSub"class="minus">-</button><input:value="value"@change="handleChange"class="inp"typ......
  • vue实现页面全屏、局部全屏等多方式全屏
    1、vuex创建全局变量在store/index中:importVuexfrom'vuex'Vue.use(Vuex)constuser={state:{//全屏fullscreen:false,},mutations:{//全屏SET_FULLSCREEN:(state,fullscreen)=>{state.fullscreen=fullscreen},},act......
  • 安装 Vue 开发者工具:装插件调试 Vue 应用
    (1)通过谷歌应用商店安装(国外网站)(2)极简插件:下载→ 开发者模式→ 拖拽安装 → 插件详情允许访问文件         https://chrome.zzzmh.cn/index下载的文件,解压。chrome浏览器,右上角点击-》更多工具=》扩展程序。打开开发者模式将解压的文件拖到空白区......
  • JVS-rules规则引擎导出与导入,确保业务连续性的关键
    在复杂的系统环境中,规则和配置的迁移、备份及共享成为了确保业务连续性和一致性的关键过程。不同的环境可能需要相同的规则和配置数据,或者我们可能需要备份这些数据以防万一。JVS规则引擎提供了规则的导出与导入功能,使用户能够在多个环境间轻松转移配置数据。每一条配置数据都有其......
  • 手动设置提示在此环境中不可导入Django
    手动设置提示在此环境中不可导入Django 环境参数添加manage.py中的代码’DJANGO_SETTINGS_MODULE’,‘codeProject.settings’ ......
  • vue2跨级组件传值
    //祖先组件importSonfrom'./Son'exportdefault{components:{Son},provide(){return{money:1000000000}}}子孙组件<template> <div>  孙子组件  <p>这个是爷爷传给我的钱:{{money}}</p> </div&......
  • vue2兄弟组件传值
    //1创建一个公共的vue实例(bus)importVuefrom'vue'constbus=newVue()exportdefaultbus<!-- brother1--><template> <div>  兄弟1组件  <p>   <button@click="send">传值给兄弟2</button>  </p&......
  • VUE 安装环境
    安装vue 工具cnpminstall-g@vue/cli验证是否安装成功vue--version创建VUE项目(vue-demo,名字要小写)vuecreatevue-demo ......
  • vue-ui
    使用vue-ui新建一个vue项目@vue/cli-ui 是vue-cli内置的一套成熟的UI。Vue-cli的3.x版本由内到外完全重写,带来了许多很棒的新特性。你可以在你的项目中选用路由、Vuex和Typescript等等特性,并为项目添加“vue-cli插件”。不过,这么多的选项也意味着它更加复杂,难以上手。因......