纯js导出并下载excel文件模板(用于导入模板下载等),还有导入excel转换成list方便后台保存等(纯前端解析excel)

上代码
页面端

<div style="display: none">
        <table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0">
            <tr>
                <th style="font-size: 18px;color: red;height: 30px">用户账号th>
                <th style="font-size: 18px;color: red">用户姓名th>
                <th style="font-size: 18px;color: red">用户密码th>
                <th style="font-size: 18px;color: red">所属部门名称th>
                <th style="font-size: 18px">手机号th>
                <th style="font-size: 18px">邮箱th>
            tr>
            <tr align="center">
                <td>模板账号1td>
                <td>张三td>
                <td>123456td>
                <td>模板1部td>
                <td>15822222222td>
                <td>[email protected]td>
            tr>
            <tr align="center">
                <td>模板账号2td>
                <td>李四td>
                <td>123456td>
                <td>模板2部td>
                <td>15833333333td>
                <td>[email protected]td>
            tr>
            <tr>
                <td colspan="6" style="color: orange;font-size: 16px;font-weight: bold" align="center">备注:红字为必填项,请勿修改列名,修改会导致数据导入失败。 默认第一行(列名)以及备注行(最后一行)不导入。td>
                <td colspan="1">td>
            tr>
        table>
    div>

js端

var base64 = function(excelFile) {
    return window.btoa(unescape(encodeURIComponent(excelFile)))
};
var tableToExcel = function(tableid, sheetName) {
    var uri = 'data:application/vnd.ms-excel;base64,';
    var template = ' +
        'xmlns="http://www.w3.org/TR/REC-html40">' +
        '{table}
'
; if (!tableid.nodeType) tableid = document.getElementById(tableid); tableid.innerHTML = tableid.innerHTML.replace('暂无筛选结果','') var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML}; var a = document.createElement("a"); a.download = sheetName + ".xls"; a.href = uri + this.base64(this.format(template, ctx));; a.click(); }; var format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }); };

调用tableToExcel 方法即可
调用传入

tableToExcel("tableExcel","人员导入模板");

tableExcel为table的id

前端解析传入的excel,先写统一工具类

<!--获取XLSX文件通用组件-->
<template>
  <span style="width: 100px">
    <a-button type="primary" icon="plus" @click="mockClick()" >批量导入</a-button>
    <!--style="visibility: hidden;width: 1px"-->
    <form id="fileForm" style="display: inline-block">
      <input type="file"
             id="File"
             style="visibility: hidden;width: 1px"
             v-on:change="getFileData($event)">
    </form>
  </span>
</template>

<script>
  import XLSX from 'xlsx'

  export default {
    name: 'getXlsxFile',
    props: {
      fields: {
        type: Array,
        default: () => {
          return []
        }
      },
      visible: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        file: ''
      }
    },
    created () {

    },
    watch: {
      fields: {
        handler(n) {
          document.getElementById('fileForm').reset()
        }
      }
    },
    mounted() {

    },
    methods: {
      mockClick() {
        document.getElementById('fileForm').reset()
        document.getElementById('File').click()
      },
      getFileData (e) {
        let files = e.target.files
        let field = this.fields

        let fileReader = new FileReader()
        if (files.length != 0) {
          fileReader.readAsBinaryString(files[0])
        }
        let data = null
        let workbook = null
        let persons = []
        let newarray = []
        // console.log(fileReader)
        fileReader.onload = (ev) => {
          try {
            data = ev.target.result
            workbook = XLSX.read(data, {
              type: 'binary'
            })
            this.$message.info('正在读取文件...')
            // let persons = [];
          } catch (ev) {
            this.$message.error("导入失败,缺失配置文件或配置文件读取错误!")
            return;
          }

          let fromTo = ''
          let array = []
          let entity = {}

          for (let sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
              fromTo = workbook.Sheets[sheet]['!ref']
              console.log(fromTo)
              persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]))
            }
          }

          if (persons.length<2){
            this.$message.error("导入失败,未读取到附件内数据!")
            return;
          }

          for(let y = 0;y<Object.keys(persons[0]).length;y++){
            let name = Object.keys(persons[0])[y]
            entity[name] = ''
          }

          for (let j = 0; j < persons.length-1; j++) {
            for(let z = 0;z<Object.keys(persons[j]).length;z++){
              if (persons[j][Object.keys(persons[j])[z]]){
                entity[Object.keys(persons[j])[z]] = persons[j][Object.keys(persons[j])[z]];
              }else{
                entity[Object.keys(persons[j])[z]] = " "
              }
            }
            array.push(entity)
          }

          console.log(array);

          for(let ar = 0;ar<array.length; ar++){
            let newentity = {}
            for(let yy = 0;yy<Object.keys(persons[0]).length;yy++){
              let name1 = Object.keys(persons[0])[yy]
              for(let fi = 0;fi<field.length;fi++){
                if(field[fi].name==name1){
                  newentity[field[fi].val] = array[ar][name1]
                  break
                }
              }
            }
            newarray.push(newentity)
          }

          this.$emit('fileData',newarray)
        }
      }
    }
  }
</script>

<style lang="less" scoped>

</style>

这是vue组件方式引入
还有纯js可用代码如下


var serviceName;

var methodName;

var grid;

var lead = function (sn,mn,gr) {
    debugger;
    serviceName = sn;
    methodName = mn;
    grid = gr;
    var inputObj = document.createElement('input');

    inputObj.setAttribute('id', '_ef');

    inputObj.setAttribute('type', 'file');

    inputObj.setAttribute('style', 'visibility:hidden');

    inputObj.setAttribute('onchange', 'aaaa(this)');

    document.body.appendChild(inputObj);

    setTimeout(function () {

    },4000);

    inputObj.click();
};



var wb;

var aaaa = function (e) {

    debugger;
    var files = e.files;

    var fileReader = new FileReader();

    fileReader.onload = function (ev) {
        try {
            var data = ev.target.result
            var workbook = XLSX.read(data, {
                    type: 'binary'
            })
            var persons = []
        } catch (ev) {
            IPLAT.alert("导入失败,缺失配置文件或配置文件读取错误!");
            return;
        }

        var fromTo = '';
        for (var sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
                fromTo = workbook.Sheets[sheet]['!ref'];
                console.log(fromTo);
                persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
            }
        }
        debugger;
        console.log(persons);
        if (persons.length<2){
            IPLAT.alert("导入失败,未读取到附件内数据!");
            return;
        }
       
        let array = []
        let entity = {}

		for(let y = 0;y<Object.keys(persons[0]).length;y++){
            let name = Object.keys(persons[0])[y]
            entity[name] = ''
        }

        for (let j = 0; j < persons.length-1; j++) {
          for(let z = 0;z<Object.keys(persons[j]).length;z++){
            if (persons[j][Object.keys(persons[j])[z]]){
              entity[Object.keys(persons[j])[z]] = persons[j][Object.keys(persons[j])[z]];
            }else{
              entity[Object.keys(persons[j])[z]] = " "
            }
          }
          array.push(entity)
        }

          console.log(array);

       for(let ar = 0;ar<array.length; ar++){
         let newentity = {}
         for(let yy = 0;yy<Object.keys(persons[0]).length;yy++){
           let name1 = Object.keys(persons[0])[yy]
           for(let fi = 0;fi<field.length;fi++){
             if(field[fi].name==name1){
               newentity[field[fi].val] = array[ar][name1]
               break
             }
           }
         }
         newarray.push(newentity)
       }

       return newentity;
    };
    if (files.length != 0) {
        fileReader.readAsBinaryString(files[0]);
    }
};

persons为解析之后的数组,后面都是代码处理 newentity为最终返回的列表
所需js工具包下载
下载地址
添加链接描述
如无法下载,可搜索两个js文件,贴入即可
xlsx.core.min.js,xlsx.full.min.js 关键字:xlsx解析
end

你可能感兴趣的:(工具包,javascript,excel,vue.js,html)