VUE3 excel上传导入,和下载导出

--------------导入上传----------------
//=========================template页面===========================
<div class="box">
      <el-upload
        accept=".xlsx, .xls, .csv"
        ref="uploadRef"
         class="upload-demo"
      action=""
      :on-change="handleChange"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :auto-upload="false"
      >
        <template #trigger>
          <el-button type="primary">开始上传</el-button>
        </template>
      </el-upload>
    </div>
    <div class="box1">
      <el-upload
        accept=".xlsx, .xls, .csv"
        ref="uploadRef"
         class="upload-demo"
      action=""
      :on-change="handleChange"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :auto-upload="false"
        style="height: 100%"
        drag
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处或<em>点击上传</em></div>
      </el-upload>
    </div>
//=========================js===========================
import axios from "api/api";
import { getCurrentInstance, reactive, toRefs } from "@vue/runtime-core";
export default {
  setup() {
    const { proxy } = getCurrentInstance();
    let state = reactive({
      loading: false,
      fileTemp: [],
      file: [],
    });
    let methods = {
      dataGoUp: async (arr) => {
        try {
          state.loading = true;
          const { data } = await axios.upExcel(arr);
          console.log(data);
          if (data.code !== 200) {
            proxy.$message.error(data.message);
          } else {
            proxy.$message.success(data.message);
          }
        } catch (error) {
          console.log(error);
        }
        state.loading = false;
      },
      importfxx: (obj) => {
        let _this = proxy;
        // let inputDOM = proxy.$refs.inputer;
        // 通过DOM取文件数据

        state.file = event.currentTarget.files[0];   //点击上传
        state.file=obj                 //点击和拖拽都可以上传

        var rABS = false; //是否将文件读取为二进制字符串
        var f = state.file;

        var reader = new FileReader();
        //if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function (f) {
          var binary = "";
          var rABS = false; //是否将文件读取为二进制字符串
          // var pt = proxy;
          var wb; //读取完成的数据
          var outdata;
          var reader = new FileReader();
          reader.onload = function (e) {
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i]);
            }
            //此处引入,用于解析excel
            var XLSX = require("xlsx");
            if (rABS) {
              wb = XLSX.read(btoa(fixdata(binary)), {
                //手动转化
                type: "base64",
              });
            } else {
              wb = XLSX.read(binary, {
                type: "binary",
              });
            }
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
            //outdata就是读取的数据(不包含标题行即表头,表头会作为对象的下标)
            //此处可对数据进行处理
            let arr = [];
            outdata.map((v) => {
              let obj = {};
              obj.mobile = v["联系方式"];
              obj.role = v["姓名"];
              obj.undefined = v["操作"];
              obj.username = v["角色"];
              arr.push(obj);
            });
            _this.da = arr;
            _this.dalen = arr.length;
            console.log(arr);
    // 调用上传方法
            methods.dataGoUp(arr);
            return arr;
          };
          reader.readAsArrayBuffer(f);
        };
        if (rABS) {
          reader.readAsArrayBuffer(f);
        } else {
          reader.readAsBinaryString(f);
        }
      },
     // 只要状态改变就会触发,不管是上传还是上传失败
      handleChange: (file, fileList) => {
        state.fileTemp = file.raw;
        if (state.fileTemp) {
          if (
            state.fileTemp.type ==
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
            state.fileTemp.type == "application/vnd.ms-excel"
          ) {
            methods.importfxx(state.fileTemp);
          } else {
            proxy.$message({
              type: "warning",
              message: "附件格式错误,请删除后重新上传!",
            });
          }
        } else {
          proxy.$message({
            type: "warning",
            message: "请上传附件!",
          });
        }
      },
      //超出最大上传文件数量时的处理方法
      handleExceed: () => {
        proxy.$message({
          type: "warning",
          message: "超出最大上传文件数量的限制!",
        });
        return;
      },
      //移除文件的操作方法
      handleRemove: (file, fileList) => {
        state.fileTemp = null;
      },
    };

    return {
      ...toRefs(state),
      ...methods,
    };
  },
};
================================css样式================================
.excel-upload-input {
  display: none;
  z-index: -9999;
}
.drop {
  border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
.upload {
  margin-top: 150px;
}
.box {
  float: left;
  border: 1px dashed #bbb;
  width: 350px;
  max-height: 160px;
  text-align: center;
  line-height: 160px;
}
.box1 {
  box-sizing: border-box;
  :deep .el-upload-dragger {
    padding: 0;
    border: none;
    width: 340px;
    height: 110px;
  }
  float: left;
  padding-top: 30px;
  border: 1px dashed #bbb;
  width: 350px;
  min-height: 160px;
  text-align: center;
}
---------------------导出下载-----------------------
<el-button @click="dialogVisible = true" type="success"
        >excel导出</el-button
      >
 <!-- excel 导出 -->
    <el-dialog v-model="dialogVisible" title="导出为 excel" width="30%">
      <el-input v-model="excelTitle" value="员工管理表"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="excelOutGo">导出</el-button>
        </span>
      </template>
    </el-dialog>
===============================js============================
//----------插件引入-----------------
import * as XLXS from "xlsx";
import FileSaver from "file-saver";
export default {
  setup() {
    const state = reactive({
      excelTitle: "表格标题1",
})
    let methods = {
    //--------------导出方法------------
      excelOutGo: async () => {
        // const tableList= await axios.getAllList();
        // 设置当前日期
      // let time = new Date();
      // let year = time.getFullYear();
      // let month = time.getMonth() + 1;
      // let day = time.getDate();
      let name =state.excelTitle ; // 导出文件名,data或者state定义好的数据
      // const filename = state.excelTitle; // 通过id,获取导出的表格数据
      // 用这个的话获取到页面里的表格数据
      const wb = XLXS.utils.table_to_book(document.getElementById("table"), {
        raw: true,
      });
      const wbout = XLXS.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: "application/octet-stream",
          }),
          name + ".xlsx"
        );
      } catch (e) {
        console.log(e);
      }
      return wbout;
      },
    };
    return {
      ...toRefs(state),
      ...methods,
    };
  },
};
</script>
 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值