导入 导出excel表

<Button
          @click="open_import"
          type="primary"
          style="margin-right: 10px"
          >导入学生</Button
        >
        <Button
          type="primary"
          @click="downloadData()"
        >导出学生</Button
        >
    <!-- 批量导入 -->
    <Modal
      :mask-closable="false"
      v-model="import_flag"
      class="modal1"
      title="导入学生"
    >
      <div style="margin-left: 20px">
        <Form>
          <FormItem>
            <div>
              <p style="font-size: 16px; color: #333">
                导入前请先下载模板
                <Button type="primary" @click="download"
                  >下载学生信息模板</Button
                >
              </p>
            </div>
          </FormItem>
          <FormItem>
            <div class="flex" v-if="import_flag">
              <Upload action accept=".xls,.xlsx" :before-upload="handleUpload">
                <div v-if="!import_img" style="display: flex">
                  <Button
                    type="primary"
                    icon="ivu-icon ivu-icon- iconfont icon-shangchuan"
                    >上传excel</Button
                  >
                </div>
                <img
                  width="88px"
                  height="94px"
                  v-else
                  src="@/assets/img/my_lesson/excel.png"
                  alt
                />
              </Upload>
              <span
                class="theme_color"
                style="
                  margin-left: 10px;
                  font-size: 16px;
                  color: black !important;
                "
                >只能上传xlsx/xls文件</span
              >
            </div>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button @click="import_flag = false">取消</Button>
        <Button @click="ok_import" :loading="excel_flag" type="primary"
          >保存</Button
        >
      </div>
    </Modal>

<script>
import table2excel from "@/utils/table2excel.js";
export default {
  data() {
    return {
    import_flag: false, //导入学生弹窗
     form_data: undefined, //表格对象
      import_img: false, //excel 图片
      import_obj: {
        file: undefined,
      },
      excel_flag: false, //导入 确定动画
      exit_data: [], //导入 错误信息
    }
  },
methods: {
//导出
downloadData() {
      const file_name = "学生字典信息";
      const file_columns = [
        {
          title: "序号",
          type: "index",
          align: "center",
        },
        {
          title: "学生姓名",
          key: "username",
          align: "center",
        },
        {
          title: "登录账号",
          key: "loginname",
          align: "center",
        },
        {
          title: "性别",
          key: "usersex",
          align: "center",
        },
        {
          title: "学生手机号",
          key: "userphone",
          align: "center",
        },
        {
          title: "民族",
          key: "nation",
          align: "center",
        },
        {
          title: "学生身份证号",
          key: "cardid",
          align: "center",
        },
        {
          title: "户口所在地",
          key: "hkareaname",
          align: "center",
        },
        {
          title: "现住址",
          key: "xzareaname",
          align: "center",
        },
        {
          title: "学生证件照地址",
          key: "idphoto",
          align: "center",
        },
        {
          title: "父亲姓名",
          key: "fathername",
          align: "center",
        },
        {
          title: "父亲身份证号",
          key: "fathercardid",
          align: "center",
        },
        {
          title: "父亲手机号",
          key: "fatherphone",
          align: "center",
        },
        {
          title: "母亲姓名",
          key: "mothername",
          align: "center",
        },
        {
          title: "母亲身份证号",
          key: "mothercardid",
          align: "center",
        },
        {
          title: "母亲手机号",
          key: "motherphone",
          align: "center",
        },
        {
          title: "身份证正面地址",
          key: "cardzm",
          align: "center",
        },
        {
          title: "身份证反面地址",
          key: "cardfm",
          align: "center",
        },
        {
          title: "户口本首页地址",
          key: "householdzm",
          align: "center",
        },
        {
          title: "户口本本人页地址",
          key: "householdfm",
          align: "center",
        },
        {
          title: "审核状态",
          key: "checkstate",
          align: "center",
        },
      ];
      udict_list_dictstu({}).then((data) => {
        if (data.code === 0) {
          let file_data = data.obj.map((v) => {
            v.username = v.username || "";
            v.loginname = v.loginname || "";
            v.usersex =
              v.usersex === 1 ? "男" : v.usersex === 2 ? "女" : "未知";
            v.userphone = v.userphone || "";
            v.nation = v.nation || "";
            v.cardid = v.cardid || "";
            v.hkareaname = v.hkareaname || "";
            v.xzareaname = v.xzareaname || "";
            v.idphoto = v.idphoto || "";
            v.fathername = v.fathername || "";
            v.fathercardid = v.fathercardid || "";
            v.fatherphone = v.fatherphone || "";
            v.mothername = v.mothername || "";
            v.mothercardid = v.mothercardid || "";
            v.motherphone = v.motherphone || "";
            v.cardzm = v.cardzm || "";
            v.cardfm = v.cardfm || "";
            v.householdzm = v.householdzm || "";
            v.householdfm = v.householdfm || "";
            let checkstate = "";
            if (v.checkstate === 1) {
              checkstate = "待审核";
            } else if (v.checkstate === 3) {
              checkstate = "审核通过";
            } else if (v.checkstate === 4) {
              checkstate = "审核不通过";
            } else if (v.checkstate === -1) {
              checkstate = "已注册";
            } else if (v.checkstate === -2) {
              checkstate = "未注册";
            }
            v.checkstate = checkstate;
            return v;
          });
          this.dataToExcel(file_columns, file_data, file_name);
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    dataToExcel(columns, data, file_name) {
      table2excel(columns, data, file_name);
    }, 
   // 下载模板
    download() {
      let url = "@/../doc/student.xls";  //模版文件路径
      const a = document.createElement("a"); // 创建a标签
      a.setAttribute("download", "学生信息模版"); // download属性
      a.setAttribute("href", url); // href链接
      a.click(); // 自执行点击事件
    },
    // 上传文件
    handleUpload(file) {
      this.import_obj.file = file;
      let str = file.name.split(".");
      let suffix = str[str.length - 1];
      suffix = suffix.toLowerCase();
      if (suffix === "xls" || suffix === "xlsx") {
        this.import_img = true;
        this.form_data = new FormData();
        this.form_data.append("file", file);
        // this.form_data.append("schoolid", this.userInfo.content.schoolid);
        this.form_data.append("createid", this.userInfo.userid);
        // this.form_data.append("classid", this.form_list.classid);
        // this.form_data.append("groupid", 1);
      } else {
        this.$Message.error("请上传excel文件");
      }
      return false;
    },
    // 批量导入确定
    ok_import() {
      if (!this.form_data) {
        this.$Message.error("请选择上传文件");
        return;
      }
      this.excel_flag = true;
      udict_import(this.form_data).then((res) => {
        this.excel_flag = false;
        if (res.code == 0) {
          if (res.obj.code == 0) {
            this.$Message.success(res.msg);
            this.import_flag = false;
            this.init();
          } else {
            this.import_img = false;
            this.exit_flag = true;
            this.exit_data.usersExisted = res.obj.usersExisted.map((v) => {
              if (v.usersex == 1) {
                v.usersex = "男";
              } else if (v.usersex == 2) {
                v.usersex = "女";
              } else {
                v.usersex = "未知";
              }
              return v;
            });
            this.exit_data.usersExisted_length = res.obj.usersExisted.length;
            this.init();
          }
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    //导入学生按钮 每次参数都初始化
    open_import() {
      this.form_data = undefined;
      this.import_flag = true;
      this.excel_flag = false;
      this.import_img = false;
      this.import_obj.file = undefined;
    },
}
}
</script>

Excel

/* eslint-disable */
/* 
可以导出合并表头的表格为Excel
*/
let idTmr;
const getExplorer = () => {
    let explorer = window.navigator.userAgent;
    //ie
    if (explorer.indexOf("MSIE") >= 0) {
        return 'ie';
    }
    //firefox

    else if (explorer.indexOf("Firefox") >= 0) {
        return 'Firefox';
    }
    //Chrome
    else if (explorer.indexOf("Chrome") >= 0) {
        return 'Chrome';
    }
    //Opera
    else if (explorer.indexOf("Opera") >= 0) {
        return 'Opera';
    }
    //Safari
    else if (explorer.indexOf("Safari") >= 0) {
        return 'Safari';
    }
}
// 判断浏览器是否为IE
const exportToExcel = (data, name) => {

    // 判断是否为IE
    if (getExplorer() == 'ie') {
        tableToIE(data, name)
    } else {
        tableToNotIE(data, name)
    }
}

const Cleanup = () => {
    window.clearInterval(idTmr);
}

// ie浏览器下执行
const tableToIE = (data, name) => {
    let curTbl = data;
    let oXL = new ActiveXObject("Excel.Application");

    //创建AX对象excel
    let oWB = oXL.Workbooks.Add();
    //获取workbook对象
    let xlsheet = oWB.Worksheets(1);
    //激活当前sheet
    let sel = document.body.createTextRange();
    sel.moveToElementText(curTbl);
    //把表格中的内容移到TextRange中
    sel.select;
    //全选TextRange中内容
    sel.execCommand("Copy");
    //复制TextRange中内容
    xlsheet.Paste();
    //粘贴到活动的EXCEL中

    oXL.Visible = true;
    //设置excel可见属性

    try {
        let fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
    } catch (e) {
        print("Nested catch caught " + e);
    } finally {
        oWB.SaveAs(fname);

        oWB.Close(savechanges = false);
        //xls.visible = false;
        oXL.Quit();
        oXL = null;
        // 结束excel进程,退出完成
        window.setInterval("Cleanup();", 1);
        idTmr = window.setInterval("Cleanup();", 1);
    }
}

// 非ie浏览器下执行
const tableToNotIE = (function () {
    // 编码要用utf-8不然默认gbk会出现中文乱码
    const uri = 'data:application/vnd.ms-excel;base64,',
        template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';

    const base64 = function (s) {
        return window.btoa(unescape(encodeURIComponent(s)));
    }

    const format = (s, c) => {
        return s.replace(/{(\w+)}/g,
            (m, p) => {
                return c[p];
            })
    }

    return (table, name) => {
        const ctx = {
            worksheet: name,
            table
        }

        const url = uri + base64(format(template, ctx));

        // if (navigator.userAgent.indexOf("Firefox") > -1){
        //  window.location.href = url
        // } else {
            const aLink = document.createElement('a');
            aLink.href = url;
            aLink.download = `${name || ''}.xls`;
            let event;
            if (window.MouseEvent) {
                event = new MouseEvent('click');
            } else {
                event = document.createEvent('MouseEvents');
                event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            }
            aLink.dispatchEvent(event);
        // }
    }
})()

// 导出函数
const table2excel = (column, data, excelName) => {
    const typeMap = {
        image: getImageHtml,
        text: getTextHtml
    }
    function getMergeData(item) {
        let mergeStr = "";
        if (item.rowspan) {
            mergeStr += ` rowspan=${item.rowspan} `;
        }
        if (item.colspan) {
            mergeStr += ` colspan=${item.colspan} `;
        }
        return mergeStr;
    }
    function getTheadRow(column, theadArr = [], floor = 0) {
        if (theadArr.length == floor) {
            theadArr.push("");  
        }
        let trItem = column.reduce((result, item) => {
            let mergeData = getMergeData(item);
            result += `<th${mergeData}>${item.title}</th$>`;
            if (item.children) {
                getTheadRow(item.children, theadArr, floor + 1);
            }
            return result;
        }, '');
        if (theadArr[floor]) {
            theadArr.splice(floor, 1, theadArr[floor] + trItem);
        } else {
            theadArr.splice(floor, 1, trItem);
        }
        return theadArr;
    }
    let theadArr = getTheadRow(column);
    theadArr = theadArr.map(v => {
        return `<tr>${v}</tr>`;
    });
    let thead = `<thead>${theadArr.join("")}</thead>`;
    // thead = `<thead>
    //                      <tr>
    //                          <th rowspan="2">姓名</th>
    //                          <th colspan="2">电话</th>
    //                      </tr>
    //                      <tr>
    //                          <th>phone</th>
    //                          <th>tel</th>
    //                      </tr>
    //                  </thead>`
    let tbody = data.reduce((result, row, rowIndex) => {
        function getTbodyRow(column, colKeys = []) {
            column.forEach(item => {
                if (item.children && item.children.length > 0) {
                    getTbodyRow(item.children, colKeys);
                } else {
                    colKeys.push({
                        type: item.type,
                        key: item.key
                    });
                }
            });
            return colKeys;
        }
        let colKeys = getTbodyRow(column);
        const temp = colKeys.reduce((tds, col) => {
            let itemVal = "";
            if (col.type == "index") {
                itemVal = rowIndex + 1;
            } else {
                itemVal = row[col.key];
            }
            let newtd = typeMap[col.type == "image" ? "image" : "text"](itemVal);
            tds += newtd;
            return tds;
        }, '');
        result += `<tr>${temp}</tr>`
        return result
    }, '')

    tbody = `<tbody>${tbody}</tbody>`
    // tbody = `<tr>
    //                  <td>Bill Gates</td>
    //                  <td>555 77 854</td>
    //                  <td>555 77 855</td>
    //              </tr>`

    const table = thead + tbody;
    // 导出表格
    exportToExcel(table, excelName);

    function getTextHtml(val) {
        return `<td style="text-align: center;mso-number-format:'\@';" ng-bind="data.paySerialNo">${val}</td>`;
    }

    function getImageHtml(val, options) {
        options = Object.assign({width: 40, height: 60}, options)
        return `<td style="width: ${options.width}px; height: ${options.height}px; text-align: center; vertical-align: middle"><img src="${val}" width=${options.width} height=${options.height}></td>`
    }
}

export default table2excel
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,386评论 6 479
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,939评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,851评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,953评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,971评论 5 369
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,784评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,126评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,765评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,148评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,744评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,858评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,479评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,080评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,053评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,278评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,245评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,590评论 2 343

推荐阅读更多精彩内容