使用数组生成标题作为键,使用值作为数据,使用javascript生成excel文件

时间:2017-11-04 07:56:19

标签: javascript arrays excel

我想去从阵列中生成excel文件。我正在成功生成excel文件。但在这里我得到的不是原始设置标题和数据。我在这里写了一些代码在javascript但没有得到propare数据。那么任何人怎么办呢,请告诉我。我在下面粘贴了我的阵列。

这是我的数组=>

var xlsx = require('node-xlsx');.
var  FinalFilterArray= [];
FinalFilterArray.push({ fullName: 'love',
        username: 'lo.ve632',
        biography: '',
        externalUrl: '',
        followerCount: 10,
        followingCount: 107,
       mediaCount: 0 },
     { fullName: 'abc',
       username: '@bc',
       biography: '',
       externalUrl: '',
       followerCount: 288,
       followingCount: 261,
       mediaCount: 0 },
    { fullName: 'xyz',
      username: 'xyz',
      biography: '#This is my ',
     externalUrl: '',
     followerCount: 234,
      followingCount: 282,
     mediaCount: 17 })

我写得像这样的代码=>

 var header = [];
    var values = [];
    for (var i = 0; i < FinalFilterArray.length; i++) {
        if (i==0) {
            header.push("fullName", "username", "biography", "externalUrl", "followerCount", "followingCount", "mediaCount")
        }
        values[i] = [ FinalFilterArray[i].fullName, FinalFilterArray[i].username, FinalFilterArray[i].biography, FinalFilterArray[i].externalUrl, FinalFilterArray[i].followerCount, FinalFilterArray[i].followingCount, FinalFilterArray[i].mediaCount]
    }
    const data = [header, values]
    var buffer = xlsx.build([{ name: "mySheetName", data: data }]);

使用此代码我在excel文件中使用此数据=&gt;

fullName                 | username           | biography           |externalUrl    followerCount   followingCount  mediaCount  
love,lo.ve632,,,10,107,0 | abc,@bc,,,288,261,0 | xyz,xyz,,234,282,17| 

我的预期o / p =&gt;

fullName   | username     | biography             |externalUrl |followerCount | followingCount |    mediaCount  
 love       | lo.ve632     |                       |            | 10           | 107            |    0
 abc        | @bc          |                       |            | 288          | 261            |    0
 xyz       | xyz          |#This is my            |            | 234           | 282            |    17

1 个答案:

答案 0 :(得分:0)

使用header.push函数代替values[i]变量,例如:

header.push(FinalFilterArray[i].fullName,
    FinalFilterArray[i].username,
    FinalFilterArray[i].biography,
    FinalFilterArray[i].externalUrl, 
    FinalFilterArray[i].followerCount, 
    FinalFilterArray[i].followingCount, 
    FinalFilterArray[i].mediaCount)

并且还要改变

const data = [header]