1. 程式人生 > 其它 >vue專案-外掛xlsx的使用,匯入表格資料的處理——寫成可引用的元件(封裝元件)

vue專案-外掛xlsx的使用,匯入表格資料的處理——寫成可引用的元件(封裝元件)

vue專案-外掛xlsx的使用,匯入表格資料的處理

背景:有個專案表單資料欄位過多,為了方便快速添入資料需要將表格中的資料匯入至表單中,記錄下來,方便以後檢視。

所用外掛:xlsx

一、裝包 npm install xlsx --save

二、封裝外掛

<template>
  <div>
    <input
      class="input-file"
      type="file"
      accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel
" @change="exportData" > <button @click="btnClick">匯入引數</button> </div> </template> <script> import XLSX from 'xlsx'; export default { name: 'InputExcel', props: { accept: { type: String, default: '選擇excel檔案' } }, methods: { btnClick() { document.querySelector(
'.input-file').click(); }, exportData(event) { if (!event.currentTarget.files.length) { return; } const that = this; // 拿取檔案物件 var f = event.currentTarget.files[0]; // 用FileReader來讀取 var reader = new FileReader(); // 重寫FileReader上的readAsBinaryString方法
FileReader.prototype.readAsBinaryString = function(f) { var binary = ''; var wb; // 讀取完成的資料 var outdata; // 你需要的資料 var reader = new FileReader(); reader.onload = function(e) { // 讀取成Uint8Array,再轉換為Unicode編碼(Unicode佔兩個位元組) var bytes = new Uint8Array(reader.result); var length = bytes.byteLength; for (var i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]); } // 接下來就是xlsx了,具體可看api wb = XLSX.read(binary, { type: 'binary' }); outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); // 自定義方法向父元件傳遞資料 that.$emit('getResult', outdata); }; reader.readAsArrayBuffer(f); }; reader.readAsBinaryString(f); } } }; </script> <style scoped> .input-file { display: none; } </style>

三、頁面中引用剛封裝的xlsx元件

<template>
  <div>
      <xlsx @getResult="getMyExcelData">匯入引數</xlsx>
  </div>
</template>
<script>
import xlsx from '@/components/xlsx/xlsx';
export default {
  components: {
    xlsx
  },
  methods:{
      getMyExcelData(data) {
      // 處理你的資料
        console.log(data);
      }
   }
</script>