龙空技术网

前端实战:Vue实现数据导出导入案例

IT技术分享社区 1338

前言:

眼前同学们对“vue如何获取数据”大概比较关心,你们都需要知道一些“vue如何获取数据”的相关内容。那么小编在网上搜集了一些对于“vue如何获取数据””的相关知识,希望朋友们能喜欢,姐妹们一起来学习一下吧!

#头条创作挑战赛#

项目开发当中,列表数据的导出功能基本是每个业务系统必备的功能、另外Excel数据批量导入数据库也是比较常见的功能,一般开发都会采用POI、EasyExcel等后端框架实现,后端服务实现的话,如果涉及业务调整的话,生产环境需要重启后端服务。如果采用前端处理的话,就会方便很多,今天给大家介绍采用Vue框架集成xlsx组件的方式实现简单数据的导入、导出功能。

1、创建一个空白的vue2/vue3项目

可以通过脚手架方式创建一个vue示例项目。

需要的依赖包如下

   "dependencies": {      "element-ui": "2.10.1",    "export2excel": "0.0.1",    "file-saver": "^2.0.5",    "vue": "^2.5.2",    "vue-router": "^3.0.1",    "xlsx": "^0.17.0"  },

通过命令安装

 npm install export2excel@0.0.1 --save #导出到excel依赖包  npm install file-saver@2.0.5 --save #文件保存到客户端 npm install xlsx@0.17.0 --save #操作excel依赖包

2、创建Export.vue 示例文件

文件内容完整内容如下:

<template>  <div class="hello">    <h1>{{ msg }}</h1>    <el-row>      <el-button size="small" type="primary" @click="exportTest">导出</el-button>      <el-upload action="/" :on-change="importTest" :show-file-list="false"        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"        :auto-upload="false">        <el-button size="small" icon="el-icon-upload" type="primary">导入数据</el-button>      </el-upload>    </el-row>    <el-row>      <el-table ref="multipleTable" style="padding-top: 10px;" :data="listData" tooltip-effect="light"        highlight-current-row :header-cell-style="{          background: '#E6EAF3',          'font-size': '13px',          padding: '0px',          height: '40px',        }" v-loading="listLoading" :cell-style="{ 'font-size': '13px', padding: '0px', height: '34px' }">        <el-table-column label="序号" type="index" width="50"></el-table-column>        <el-table-column label="姓名" show-overflow-tooltip width="110">          <template slot-scope="scope">{{ scope.row.name }}</template>        </el-table-column>        <el-table-column label="年龄" show-overflow-tooltip width="">          <template slot-scope="scope">{{ scope.row.age }}</template>        </el-table-column>      </el-table>    </el-row>  </div></template><script>import { export_json_to_excel } from "@/vendor/Export2Excel";import Xlsx from 'xlsx'export default {  name: 'HelloWorld',  data() {    return {      msg: '导入导出测试',      listData: [        { name: "小明", age: 30 },        { name: "小张", age: 25 },        { name: "小李", age: 29 }      ],      listLoading: false,      xlscTitle: {        "姓名": "name",        "年龄": "age"      },       }  },  methods: {    exportTest() {      const header = [        "姓名",        "年龄"      ];      const body = [        "name",        "age",      ];      const data = this.formatJson(body, this.listData);      console.log(data);      export_json_to_excel({        header: header,// 表头        data: data, // 数据列表        filename: "用户表",// 保存文件名      });    },    //格式化json数据为导出数据 过滤掉查询的数据列不在导出的列里面的数据    formatJson(filterVal, jsonData) {      return jsonData.map((a) => filterVal.map((b) => a[b]));    },    importTest(file) {      let self = this;      const types = file.name.split('.')[1];      const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => {        return item === types      });      if (!fileType) {        this.$message.error('文件格式错误,请重新选择文件!')      }      this.file2Xce(file).then(tab => {                // 过滤,转化正确的JSON对象格式        if (tab && tab.length > 0) {          tab[0].sheet.forEach(item => {            let obj = {};            for (let key in item) {              obj[self.xlscTitle[key]] = item[key];            }            self.listData.push(obj);          });                   if (self.listData.length) {            this.$message.success('上传成功')            // 获取数据后,下一步操作          } else {            this.$message.error('空文件或数据缺失,请重新选择文件!')          }        }      })    },    // 读取文件    file2Xce(file) {      return new Promise(function (resolve, reject) {        const reader = new FileReader();        reader.onload = function (e) {          const data = e.target.result;          //var Xlsx = require("xlsx");          this.wb = Xlsx.read(data, {            type: "binary"          });          const result = [];          this.wb.SheetNames.forEach(sheetName => {            result.push({              sheetName: sheetName,              sheet: Xlsx.utils.sheet_to_json(this.wb.Sheets[sheetName])            })          })          resolve(result);        }        reader.readAsBinaryString(file.raw);      })    }  }}</script><!-- Add "scoped" attribute to limit CSS to this component only --><style scoped>h1,h2 {  font-weight: normal;}ul {  list-style-type: none;  padding: 0;}li {  display: inline-block;  margin: 0 10px;}a {  color: #42b983;}</style>

标签: #vue如何获取数据