webfont-yxw

当前的目录结构

excel的数据如下:

node识别excel,先得安装  node-xlsx,用npm或yarn都可以

npm install  node-xlsx

yarn add node-xlsx

index.js 完整代码如下:

const fs = require('fs');
const xlsx = require('node-xlsx')
// excel数据
const excelData = xlsx.parse('./excel/students.xlsx');
// 最终数据
let finalArr = [];

function handelExcel() {
  // excel的第一个sheet
  const excelSheet = excelData[0].data;
  // 表头
  const columns = excelSheet[0];
  // 表头对应的key
  const columnsObj = {
    username: '姓名',
    age: '年龄',
    gender: '性别',
    score: '分数'
  }
  let JSONKey = []
  // 设置JSON key值
  columns.forEach(item => {
    for (key in columnsObj) {
      const itemKey = columnsObj[key];
      itemKey === item ? JSONKey.push(key) : ''
    }
  })
  // 表内容
  const jsonData = excelSheet.slice(1);
  jsonData.forEach(lineItem => {
    let arrItem = {}
    lineItem.forEach((item, index) => Object.assign(arrItem, { [JSONKey[index]]: item }))
    finalArr.push(arrItem);
  })
};

handelExcel();
generatJSON('./data/data.json', JSON.stringify(finalArr, null , '\t'))


/**
 * 生成JSON文件
 * @param {*} fileName 
 * @param {*} data 
 */
function generatJSON(fileName, data) {
  fs.writeFile(fileName, data, 'utf-8', function (err) {
    if (err) {
      console.log('errr');
    } else {
      console.log('success');
    }
  })
}

 

最后执行 node index.js 即可生成文件

 

 

分类:

技术点:

相关文章:

  • 2021-11-17
  • 2021-09-08
  • 2022-01-09
  • 2021-11-16
  • 2021-12-16
  • 2022-01-01
  • 2022-01-01
  • 2022-01-01
猜你喜欢
  • 2021-08-17
  • 2021-11-23
  • 2021-11-23
  • 2021-11-23
  • 2021-09-07
  • 2022-01-01
  • 2021-09-27
相关资源
相似解决方案