當前的目錄結構node
excel的數據以下:npm
node識別excel,先得安裝 node-xlsx,用npm或yarn均可以json
npm install node-xlsxui
或spa
yarn add node-xlsxexcel
index.js 完整代碼以下:code
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 便可生成文件blog