Vue2+ElementUI实现上传Excel文件

目前在做的一个项目有个需求:上传Excel文件,实现数据的导入。和大家分享一下,第一次写,格式可能有些乱。

实现效果如下图所示:

1、实现效果图

2、Template内的代码

<template>
  <div>
    <div class="uploadDiv">
      <!-- 下载模板按钮 -->
      <el-button type="primary" @click="downloadTemplate">下载模板文件</el-button>
      <!-- 文件上传按钮 -->
      <el-button type="primary" @click="dialogVisible = true">导入党员信息</el-button>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="上传党员信息">
      <el-upload
        class="upload-demo"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :before-upload="beforeExcelUpload"
        drag
        style="text-align: center"
        :action="uploadUrl"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传Excel表格文件</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

3、script代码

<script>

export default {
  name: "",
  data() {
    return {
      uploadUrl: "你自己的上传Excel地址",
      dialogVisible: false,
    };
  },
  methods: {
    // 显示所有数据
    // 根据自己的代码从后端获取数据
    showAll() {
      ...
    },
    // 文件上传成功的处理函数
    uploadSuccess(response, file, fileList) {
      this.dialogVisible = false; // 关闭弹出框
      if (response.code == 200) {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.showAll(); // 上传成功之后重新查询列表
      } else {
        this.$message({
          message: "上传失败,系统异常",
          type: "error",
        });
      }
    },
    // 上传前对文件的格式和大小的判断
    beforeExcelUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!extension && !extension2) {
        this.$message({
          message: "上传模板只能是 xls、xlsx格式!",
          type: "error",
        });
        return false; // return false就不会走上传接口
      }
      if (!isLt2M) {
        this.$message({
          message: "上传模板大小不能超过 10MB!",
          type: "error",
        });
        return false;
      }
      return extension || extension2; // 必须要有返回值
    },
    // 下载模板文件
    downloadTemplate() {
      // 获取项目部署的基础路径
      const baseUrl = window.location.origin;
      // 构建文件的完整 URL
      // 模板文件我是存放在了项目public/template文件夹中
      let downloadUrl = `${baseUrl}/template/信息表.xlsx`;
      var a = document.createElement("a");
      a.href = downloadUrl;
      a.download = "信息表.xlsx";
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      a.remove();
    },
  },
};
</script>

以上便是Vue2+ElementUI实现上传Excel文件导入数据的功能。

Vue.js 开发环境中使用 Element UI 和相关的插件如 "vue-excel-import" 可以方便地处理 Excel 文件读取。以下是简单的步骤: 1. **安装依赖**: 首先,需要在项目中安装必要的库。运行 `npm install` 或者 `yarn add` 来安装: ```bash npm install axios file-saver js-xlsx element-ui vue-excel-import ``` 2. **引入组件和配置**: 引入 Element UI 的表格组件和其他必要组件,并在 main.js 中注册 `vue-excel-import` 插件: ```javascript import { ElTable } from 'element-ui'; import { ExcelImport } from 'vue-excel-import'; Vue.use(ExcelImport); ``` 3. **创建 Excel 读取功能**: 创建一个 Vue 组件,例如 `UploadExcel.vue`,并使用 `excel-import` 功能来接收文件并解析数据: ```html <template> <el-button @click="upload">导入 Excel</el-button> <el-table :data="tableData" ref="excelTable"> <!-- 表格列配置 --> </el-table> </template> <script> export default { data() { return { tableData: [], file: null, }; }, methods: { upload() { this.$refs['excelTable'].import({ onBefore(file) { // 这里可以预览文件、限制上传大小等操作 }, onStart({ files }) { // 显示进度条 }, onFinish(result) { const { data } = result; this.tableData = data.map((row) => row.data); // 假设每个sheet的数据是一个数组 }, onError(error) { console.error('导入失败:', error); } }, this.file); } }, // 其他生命周期钩子和选项 }; </script> ``` 4. **HTML 表单提交**: 添加一个表单元素让用户选择 Excel 文件,比如使用 `<input type="file" @change="handleFileChange">`,然后在 `handleFileChange` 函数中设置 `this.file`。 注意:实际操作中,你需要处理不同 Excel 格式的问题,例如 `.xls` 和 `.xlsx`,并且根据返回的数据格式适配表格展示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值