JSON与excel之间的相互转化(Vue)


JSON与excel之间的相互转化(Vue) 

 

这几天项目中有个需求,是对数据进行批量操作

上传时候需要把excel转为json发给后端,而在导出时需要将json转为excel文件

我是借用了xlsx这个库来完成的,在此记录一下

npm i xlsx安装相关依赖

设置一个input用于

 <input type="file"
           name="fileUploader"
           id="fileUploader"
           accept=".xls,.xlsx"
        @change="_toJSON"/>

引入对应的框架

import xlsx from 'xlsx'

excel转json

_toJson(){
    let file = e.target.files[0]
      let reader = new FileReader()
      reader.onload = (event) => {
        console.log(event);
        let data = event.target.result;
        const workbook = XLSX.read(data, {
          type: 'binary'
        });
        let resultArray = []
        workbook.SheetNames.forEach(function (sheetName) {
          console.log('workbook.Sheets[sheetName]', workbook.Sheets[sheetName]);
          const data = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { header: 1 });
          console.log('data', data);
          let mainData = data.slice(1)
          if (mainData.length > 0) {
            for (let row = 0; row < mainData.length; row++) {
              let rowData = {}
              for (let col = 0; col < data[0].length; col++) {
                rowData[data[0][col]] = mainData[row][col] || ''
              }
              resultArray.push(rowData)
            }
          } else {
            alert('至少需要一行有效数据')
          }
        })
        console.log('resultArray', resultArray);

      }
      reader.readAsBinaryString(file);
}

json转excel

_toExcel () {
      let data = [{ "业务政策": 1, "产品名称": 2, "证件号码": 5 }, { "产品名称": 2 }]
      const ws = XLSX.utils.json_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "People");
      XLSX.writeFile(wb, "sheetjs.xlsx");
    }