Vue +element realizes uploading and downloading nested multi-line data of excel files

Preparation

1. Install dependent packages

npm install -S file-saver (-S for production environment)

npm install -S xlsx

npm install -D script-loader (-D for development environment)

2. Import files

Exporting excel requires two files: Blob.js and Export2Excel.js

Link: https://pan.baidu.com/s/137U5xaym8htX_q2AaVt6Mw Extraction code: xue9

Create a new directory vendor under src, put Blob.js and Export2Excel.js into it, modify the content of the Export2Excel.js file, the following statement means to import Blob.js, pay attention to modify the path corresponding to Blob.js in your own project,

require('script-loader!vendor/Blob')

download

Download the export_json_to_excel function implementation using Export2Excel.js

First write a button and give a click event

<el-button type="primary" @click="downloadOption" icon="el-icon-download">下载</el-button>

The data format here is that the data is nested in the array

let question= [
{
    age:'60',
    name:'zhangsan',
    option:[{
    house:101,
    money:1000
},{
    house:102,
    money:2000
}]
}]

downloadOption method

 downloadOption() {
      let data = this.question;
      let newData = [];
      
      data.forEach((item,index)=>{
        console.log(item)
        newData.push([
          item.age,
          item.name,
          item.options[0].house,
          item.options[0].money,
        ]);
        if(item.options.length>1){
          for(let i=1;i<item.options.length;i++){
            if(item.standardAnswer[i]){
              let newOption=[
              '',
              '',
              item.options[i].house,
              item.options[i].money
            ]
            newData.push(newOption);
          }
        }
      });
      require.ensure([], () => {
                    const { exportJsonToExcel } = require('../../../vendor/Export2Excel')
                    const tHeader = ['age', 'namr', 'house', 'money'];
                    exportJsonToExcel(tHeader, newData, '数据报表excel');
                })
    },

Note that the second layer of data in the array here is inserted into the array in the form of a space

upload

The <el-upload> component of element is used for uploading, FileReader is used for reading, and the utils.sheet_to_json method of xlsx is used to convert the read content into json data, and we can proceed to the next step.

importExcel(file) {
      const types = file.name.split(".")[1];
      const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt", "xlw", "csv"].some(
        item => item === types
      );
      if (!fileType) {
        alert("格式错误!请重新选择");
        return;
      }
      this.file2Xce(file).then(tabJson => {
        console.log('tabJson即为excel转换成json')
    })
}
file2Xce(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = function(e) {
          const data = e.target.result;
          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);
      });
    }

Note that XLSX needs to import

import XLSX from "xlsx";

 

Guess you like

Origin blog.csdn.net/weixin_42252416/article/details/99963341