Vue + Element 实现导入导出Excel

6 篇文章 0 订阅

1、首先搭建Vue 项目(具体可参考以前文章,不再详述:https://blog.csdn.net/qq_42540989/article/details/89853923

2、引入Element(你可以引入整个 Element,或是根据需要仅引入部分组件。我们先介绍如何引入完整的 Element。)

//在main.js中引用

import ElementUi from 'element-ui'

import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUi)

3、 在components 文件夹中新建一个Vue文件

// excal.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
   <el-row>
  <el-button>默认按钮</el-button>
  <el-button type="primary">主要按钮</el-button>
  <el-button type="success">成功按钮</el-button>
</el-row>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        imageUrl: '',
        msg:'hello,Element'
      };
    },
    methods: {
    }
  }
</script>
<style scoped>

</style>
// index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import excal from '@/components/excal'
Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/enter/',
      name: 'excal',
      component: excal
    }
  ]
})

3、 运行项目

// 运行

npm run dev

4、访问  http://localhost:8080/#/enter  查看  element-ui 是否成功引入

 


5、导入导出 - -  开始引入工具库

//  file-saver      xlsx       script-loader

cnpm install -S file-saver xlsx

cnpm install -D script-loader

 6、导入代码: https://github.com/MrBaiLiJie/importExcal

// https://github.com/MrBaiLiJie/importExcal

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <!-- <el-row>
  <el-button>默认按钮</el-button>
  <el-button type="primary">主要按钮</el-button>
  <el-button type="success">成功按钮</el-button>
    </el-row>-->
    <el-upload
      class="upload-demo"
      action
      :on-change="handleChange"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :file-list="fileListUpload"
      :limit="limitUpload"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      :auto-upload="false"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只 能 上 传 xlsx / xls 文 件</div>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: "",
      msg: "hello,Element",
      limitUpload: 1,
      fileTemp: "",
      file:"",
      fileListUpload: []
    };
  },
  methods: {
    handleChange(file,fileList){
      // console.log(file)
      this.fileTemp = file.raw;
      if(this.fileTemp){
        // console.log(this.fileTemp.type)
        if(this.fileTemp.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"){
          this.importfxx(this.fileTemp)
        }else{
          this.$message({
            type:"warning",
            message:"附件格式错误,请删除后重新上传!"
          });
        }
      }
      
    },
    importfxx(obj) {
      console.log(obj)
      let _this = this;
      // 通过DOM取文件数据
      this.file = obj;
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        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]);
          }
          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就是你想要的东西
          this.da = [...outdata];
          let arr = [];
          this.da.map(v => {
            let obj = {};
            obj.code = v["设备ID"];
            obj.type = v["设备型号"];
            arr.push(obj);
          });
          return arr;
        };
        reader.readAsArrayBuffer(f);
      };

      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`);
    },
    handleRemove(file, fileList) {
      // console.log(file)
      this.fileTemp = null;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择1个文件,本次选择了 ${
          files.length
        } 个文件,共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    
  }
};
</script>
<style scoped>
</style>

6、 补充

xls 是一个特有的二进制格式,其核心结构是复合文档类型的结构,而 xlsx 的核心结构是 XML 类型的结构,采用的是基于 XML 的压缩方式,使其占用的空间更小。xlsx 中最后一个 x 的意义就在于此。

 

7、导出步骤

// 步骤

1、引入js文件

在src文件夹下新建excal文件夹,引入两个js文件     Blob.js    Export2Excel.js

// js文件 已上传至github

地址:https://github.com/MrBaiLiJie/importExcal/tree/master/src/excal

2、在main.js引入

import Blob from './excal/Blob.js'
import Export2Excel from './excal/Export2Excel.js'

3、打开Export2Excel.js

require('script-loader!file-saver');
require('script-loader!./Blob');
require('script-loader!xlsx/dist/xlsx.core.min');

这几个文件不支持import引入,所以需要script-loader来将他们挂载到全局环境下。

8、导出代码:https://github.com/MrBaiLiJie/importExcal

// https://github.com/MrBaiLiJie/importExcal

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <!-- <el-row>
  <el-button>默认按钮</el-button>
  <el-button type="primary">主要按钮</el-button>
  <el-button type="success">成功按钮</el-button>
    </el-row>-->
    <!-- 导出 -->
    <el-button @click="outExe">导出</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: "",
      msg: "hello,Element",
      limitUpload: 1,
      fileTemp: "",
      file: "",
      fileListUpload: [],
      excelData:[],
      dataList:[{userId:1,name:'小白',age:'18',status:"上学"},{userId:2,name:'小黑',age:'22',status:"待业"},{userId:3,name:'小红',age:'28',status:"就业"}]
    };
  },
  methods: {
    // 导出
    outExe() {
      this.$confirm("此操作将导出excel文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.excelData = this.dataList; //你要导出的数据list。
          this.export2Excel();
        })
        .catch(() => {});
    },
    export2Excel() {
      var that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require("../excal/Export2Excel"); //这里必须使用绝对路径,根据自己的命名和路径
        const tHeader = [
          "userId",
          "name",
          "age",
          "status",
        ]; // 导出的表头名
        const filterVal = [
          "userId",
          "name",
          "age",
          "status",
        ]; // 导出的表头字段名
        const list = that.excelData;
        // that.excelData为传入的数据
        const data = that.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, `测试导出excel`); // 导出的表格名称,根据需要自己命名
        // tHeader为导出Excel表头名称,`xxxxxx`即为导出Excel名称
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    }
  }
};
</script>
<style scoped>
</style>

9、参考文献

element-ui官方文档:https://element.eleme.io/#/zh-CN/component/upload

https://segmentfault.com/a/1190000018993619#item-3-5

  • 33
    点赞
  • 154
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
要在Vue 2.x中使用Element UI导入导出Excel,你需要安装element-ui和file-saver插件。 首先,在Vue项目中使用npm或yarn安装Element UI和file-saver插件: ``` npm install element-ui file-saver --save ``` 然后,在Vue组件中引入所需的文件: ```javascript import { Button, Table } from 'element-ui' import XLSX from 'xlsx' import FileSaver from 'file-saver' ``` 在组件中,你需要定义导入导出Excel的方法。下面是一个简单的示例: ```javascript methods: { // 导入Excel handleImportExcel(file) { const reader = new FileReader() reader.onload = (e) => { const data = new Uint8Array(e.target.result) const workbook = XLSX.read(data, { type: 'array' }) const worksheet = workbook.Sheets[workbook.SheetNames[0]] const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }) // 处理导入Excel数据 console.log(jsonData) } reader.readAsArrayBuffer(file.raw) }, // 导出Excel handleExportExcel() { const jsonData = [ ['姓名', '年龄', '性别'], ['张三', 18, '男'], ['李四', 20, '女'] ] const worksheet = XLSX.utils.aoa_to_sheet(jsonData) const workbook = XLSX.utils.book_new() XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1') const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' }) const excelData = new Blob([excelBuffer], { type: 'application/octet-stream' }) FileSaver.saveAs(excelData, 'example.xlsx') } } ``` 最后,在模板中使用Element UI的Button和Table组件,分别绑定导入导出Excel的方法: ```html <template> <div> <el-button type="primary" @change="handleImportExcel">导入Excel</el-button> <el-table :data="tableData"> <!-- 表格内容 --> </el-table> <el-button type="success" @click="handleExportExcel">导出Excel</el-button> </div> </template> ``` 这样,你就可以在Vue项目中使用Element UI导入导出Excel了。当用户选择一个Excel文件时,`handleImportExcel`方法将会被触发,并将Excel数据转换为JSON数据进行处理。而`handleExportExcel`方法则会将JSON数据转换为Excel文件并进行下载。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值