好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

vue+elementUl导入文件方式(判断文件格式)

elementUl导入文件(判断文件格式)

使用el-elment 的el-dropdown组件来写下拉菜单效果。

下载模板比较简单,直接点击跳转页面,用window.open打开一个新的浏览器窗口方式下载模板文件。

选择文件,用组件el-upload。需要做一个提示[只能上传Excel文件],用el-tooltip组件。

上传文件需要在before-upload进行判断文件格式。

判断文件格式的思路

是获取文件的后缀名,如果不是.xlsx就返回false,提示[文件格式只能是.xlsx!]

获取文件后缀名用到了2个方法。lastIndexOf()和substring()

lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索

stringObject.substring(start,stop)

参数 描述 start 必需。一个非负的整数,规定要提取的子串的第一个字符在 stringObject 中的位置。 stop

可选。一个非负的整数,比要提取的子串的最后一个字符在 stringObject 中的位置多 1。

如果省略该参数,那么返回的子串会一直到字符串的结尾。

html

        <el-dropdown style="margin-left: 10px">
          <el-button type="primary">
            导入教师
            <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <span @click="modelDown">下载模板</span>
            </el-dropdown-item>
            <el-dropdown-item>
              <el-upload
                ref="upload"
                action="/api/teacher/import"
                :limit="1"
                :data="uploadFile"
                :on-error="uploadError"
                :before-upload="beforeUpload"
                :on-success="uploadSuccess"
              >
                <div class="right">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="只能上传Excel文件"
                    placement="right"
                  >
                    <el-button type="text">选择文件</el-button>
                  </el-tooltip>
                </div>
              </el-upload>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

data:

  data() {
 
    return {
      uploadFile: {}, //拼接导入文件参数
      tableData: [], // 页面table显示的数据
 
    };
  },

methods

    // 下载模版
    modelDown() {
      window.open(
        "https://linkjoint-star.oss-cn-hongkong.aliyuncs测试数据/excel-template/教师导入模板.xlsx"
      );
    },
    // 提取文件后缀名
    getSuffix(str) {
      const fileExtension = str.substring(str.lastIndexOf(".") + 1);
      return fileExtension;
    },
    //导入前判断
    beforeUpload(file) {
      let suffix = this.getSuffix(file.name);
      if (suffix !== "xlsx") {
        this.$message.error("文件格式只能是.xlsx");
        return false;
      }
    },
    //导入完成后提示
    uploadSuccess(res, file) {
      console.log("res", res);
      if (res.status_code == 200) {
        if (res.data.status == 200) {
          this.$message({ message: `${res.data.msg}`, type: "success" });
          this.getData();
        } else {
          this.$message({ message: `${res.data.msg}`, type: "warning" });
        }
      } else {
        this.$message.error("服务器错误");
      }
      this.$refs.upload.clearFiles();
    },
    //导入错误提示
    uploadError(err, file) {
      let error = JSON.parse(err.message);
      console.log(file);
      if (error.status_code == 422) {
        this.$message.error(error.message);
      }
      this.$refs.upload.clearFiles();
    },

vue element导出导入

导出(下载)

Vue+Element后端导出Excel

从后台导出时,刚取到的文件是个流文件,需要把流文件进行转换。

<el-button class=".el-dropdown-menu__item i" ?type="primary"?
icon="el-icon-upload2" @click="downloadTemplate()" >导出模板</el-button>

?downloadTemplate() {
? ? ? exportTemplate()
? ? ? ? .then(res => {
? ? ? ? ? if (!res) {
? ? ? ? ? ? return;
? ? ? ? ? }
? ? ? ? ? // 兼容IE浏览器
? ? ? ? ? if (window.navigator && window.navigator.msSaveOrOpenBlob) {
? ? ? ? ? ? window.navigator.msSaveOrOpenBlob(
? ? ? ? ? ? ? new Blob([res.data]),
? ? ? ? ? ? ? `文件名称.xlsx`
? ? ? ? ? ? );
? ? ? ? ? } else {
? ? ? ? ? ? let url = window.URL.createObjectURL(new Blob([res.data])); //取到url。创建一个 DOMString,其中包含一个表示参数中给出的对象res的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。
? ? ? ? ? ? let link = document.createElement("a"); //触发鼠标事件对象
? ? ? ? ? ? link.style.display = "none"; //清除a标签样式
? ? ? ? ? ? link.href = url; //设置下载地址
? ? ? ? ? ? link.setAttribute("download", `文件名称.xlsx`); //给a标签添加download属性,并为其赋值
? ? ? ? ? ? document.body.appendChild(link); //向节点添加一个子节点
? ? ? ? ? ? link.click(); //执行click事件
? ? ? ? ? }
? ? ? ? })
? ? ? ? .catch(error => {
? ? ? ? });
? ? },

前端导出Excel的方法,后期有机会再总结吧。

导入(上传)

Vue+Element后端导入Excel

先读取excel,通过接口把读出的数据result传给后台

?<el-upload
? ? ref="upload"
? ? :show-file-list="false"
? ? :on-change="readExcel"
? ? :auto-upload="false"
? ? :limit="1"
? ? :action="'/api/xxxx/xxxxxxxxxxxxx/'"
? ? accept=".xlsx"
? ? style="width:100%;"
? >
? <el-button
? ? ?type="primary"
? ? ?class=".el-dropdown-menu__item i"
? ? ?slot="trigger"
? ? ?icon="el-icon-download"
? ? ?>导入</el-button>
</el-upload>

import XLSX from "xlsx";

读取excel

// 读取excel
? ? readExcel(file) {
? ? ? var reader = new FileReader(); //启动读取指定的File 内容
? ? ? reader.readAsArrayBuffer(file.raw); //当读取操作完成时,会触发一个 load 事件,从而可以使用 reader.onload 属性对该事件进行处理。
? ? ? reader.onload = e => { ? ? ? ?//获取文件数据
? ? ? ? const data = e.target.result; //XLSX读取文件
? ? ? ? const wb = XLSX.read(data, { type: "array" }); ?//获取第一张表
? ? ? ? const wsname = wb.SheetNames[0];
? ? ? ? const ws = wb.Sheets[wsname];
? ? ? ? var result = XLSX.utils.sheet_to_json(ws, { header: 1 });
? ? ? ? this.$refs.upload.clearFiles(); //清除当前 files
? ? ? ? if (result.length < 2503) {
? ? ? ? ? this.dataDetail(result);
? ? ? ? } else {
? ? ? ? ? this.$message("每次导入数据最多2500条");
? ? ? ? }
? ? ? ? return result;
? ? ? };
? ? },

//通过接口把读出来的result传给后台
dataDetail(result) {
//result内容格式的校验、必填项的校验
? importReord(result)
? ? ? ? .then(res => {
? ? ? ? ? ? this.getRecordList();
? ? ? ? ? ? if (res.data.msg == "批量新增成功") {
? ? ? ? ? ? ? this.$message({
? ? ? ? ? ? ? ? message: "数据导入成功",
? ? ? ? ? ? ? ? type: "success"
? ? ? ? ? ? ? });
? ? ? ? ? ? }
? ? ? ? ? })
? ? ? ?.catch(error => {
? ? ? ? ? ? if (error.response.status == 403) {
? ? ? ? ? ? ? this.$message.error("无操作权限");
? ? ? ? ? ? } else {
? ? ? ? ? ? ? this.$message.error("数据导入失败");
? ? ? ? ? ? }
? ? ? ? ? });
}

校验时间格式

格式 : 2020-02-12 12:00

?//校验时间格式
? ? istimeCheck(keyword) {
? ? ? // let emIP = this.periodCheck.replace(/\s+/g, ""); //循环去空
? ? ? let emIP = this.periodCheck.replace(/(^\s*)|(\s*$)/g, ""); //去除首尾空格
? ? ? let timeArray = emIP.split("-"); //把字符串转换为数组
? ? ? var result = timeArray.map(function(item, index, timeArray) {
? ? ? ? // var reg = /^[1-9]\d{3}.(0[1-9]|1[0-2]).(0[1-9][0-1][0-9]|0[1-9]2[0-3]|[1-2][0-9][0-1][0-9]|[1-2][0-9]2[0-3]|3[0-1][0-1][0-9]|3[0-1]2[0-3]):[0-5][0-9]$/;
? ? ? ? var reg = /^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3}).(((0[13578]|1[02]).(0[1-9]|[12][0-9]|3[01]))|((0[469]|11).(0[1-9]|[12][0-9]|30))|(02.(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00)).02.29)) ([0-1][0-9]|2[0-3]):([0-5][0-9])$/;
? ? ? ? return reg.test(item);
? ? ? });
? ? ? if (result.indexOf(false) > -1) {
? ? ? ? return false;
? ? ? } else {
? ? ? ? return true;
? ? ? }
? ? }

校验IP地址格式

格式 : 10.1.1.12 或 10.1.12/24

?//校验IP地址格式
? ? isValidIP(keyword) {
? ? ? let emIP = this.OValidIP.replace(/\s+/g, ""); //字符串去空
? ? ? if (emIP.indexOf("/") > -1) {
? ? ? ? var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\/(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
? ? ? ? return reg.test(emIP);
? ? ? } else {
? ? ? ? var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
? ? ? ? return reg.test(emIP);
? ? ? }
? ? },

注意:在进行格式检验时,一定要记得判断值为" "或者undefined的情况,否则很容易出现bug。

Vue+Element前端导入Excel

前端导入需要先读取excel,把读出的数据渲染在前端界面上(如:table表格中,此时如果刷新界面,那数据就会没有了),然后通过提交或者保存的方式传给后台。读取excel的方法上面已经有了。 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

查看更多关于vue+elementUl导入文件方式(判断文件格式)的详细内容...

  阅读:32次