上一篇寫的是Excel轉化為JSON,今天寫一篇JSON轉化為Excel的。
首先得安裝 excel-export
查看原文檔: https://www.npmjs.com/package/node-excel-export
yarn add excel-export
or
npm install excel-export
以上兩種方式隨便選用一種都行。
代碼實現如下:
1 const excelPort = require('excel-export'); 2 const fs = require('fs'); 4 // JSON數據(此處作為示例,JSON數據寫到代碼當中,實際過程中,先生成JSON文件,然后通過fs.readFile讀取文件內容,然后拿讀取到的數據生成Excel) 5 const arrData = [ 6 { 7 "name": "MacBook Pro", 8 "size": 13, 9 "price": 13000, 10 }, 11 { 12 "name": "IPhone 7", 13 "size": 32, 14 "price": 5000, 15 }, 16 { 17 "name": "IPhone 8", 18 "size": 128, 19 "price": 8000, 20 } 21 ]; 22 const generateExcel = (datas) => { 23 /** 24 * 定義一個空對象,來存放表頭和內容 25 * cols,rows為固定字段,不可修改 26 */ 27 const excelConf = { 28 cols: [], // 表頭 29 rows: [], // 內容 30 }; 31 // 表頭 32 for(let key in datas[0]){ 33 excelConf.cols.push({ 34 caption: key, 35 type: 'string', // 數據類型 36 width: 100, // 寬度 37 }) 38 } 39 // 內容 40 datas.forEach(item => { 41 // 解構 42 const { name, size, price } = item 43 excelConf.rows.push([name, size, price]) 44 }) 45 // 調用excelPort的方法,生成最終的數據 46 const result = excelPort.execute(excelConf); 47 // 寫文件 48 fs.writeFile('./excel/goods.xlsx', result, 'binary', err => { 49 if(!err){ 50 console.log('生成成功!') 51 } 52 }) 53 } 54 generateExcel(arrData);