前端實戰: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>

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/X3nYXyK012vZ-KPiBerd6Q