node生成Excel

上一篇写的是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);

猜你喜欢

转载自www.cnblogs.com/webfont-yxw/p/11966720.html