Nodejs获取网络数据并生成Excel表格

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

Nodejs的模版中有很多关于Excel表格的,这里我简单介绍一下我使用过的一个模块的使用。

首先,先安装Excel的模块:

npm install node-xlsx

然后,在代码中引入模块:

var xlsx = require('node-xlsx');

最后,获取数据并写入Excel:

var fs = require('fs');
var xlsx = require('node-xlsx');

var ajax = require('./ajax.js');
start();
function start() {
    ajax.ajax({
        url: "http://yuntuapi.amap.com/datamanage/data/list",
        type: "GET",
        data: {
            tableid: "XXX",//53eacbe4e4b0693fbf5fd13b
            key: "XXX"
        },
        success: function (data) {
            var myDatas = [];
            var datas = (JSON.parse(data)).datas;
            var count = 0;
            for (var index in datas) {
                var account = datas[index];
                var colum = [];
                var names;
                if (index == 0) {
                    names = [];
                }
                for (var index2 in account) {
                    if (index == 0)
                        names.push(index2);
                    var value = account[index2];
                    if (value == null) {
                        value = "";
                    }
                    colum.push(value);
// console.log(account);
                }
                if (index == 0) {
                    myDatas.push(names);
                }
                myDatas.push(colum);

                if (index == datas.length - 1) {
                    writeXls(myDatas);
                }
            }
            console.log(myDatas.length);
        }
    });
}
function writeXls(datas) {
    var buffer = xlsx.build({worksheets: [
        {"name": "Group", "data": datas}
    ]});
    fs.writeFileSync("Group.csv", buffer, 'binary');
}
function parseXls() {
    var obj = xlsx.parse('myFile.xlsx');
    console.log(obj);
}

Ajax 部分的代码:

var https = require("https");
var http = require("http");
var Url = require("url");
var querystring = require('querystring');

// 默认值
var defaultSetting = {
    // 如果返回false可以取消本次请求
    beforeSend: function (req) {
    },
    complete: function (req) {
    },
    data: '', // Object, String
    dataType: 'JSON',
    error: function () {
    },
    headers: {}, // {k:v, ...}
    statusCode: {},
    success: function (data) {
    },
    timeout: 10,
    type: 'GET', // GET, POST
    url: "www.baidu.com"
};

/** * */
function ajax(settings) {
    // ajaxlbs.js(settings)
    if (typeof settings === "object") {
        // 处理默认值继承
        // todo ...
        for (key in defaultSetting) {
            if (settings[key] == null) {
                settings[key] = defaultSetting[key];
            }
        }
    }

    var params = Url.parse(settings.url, true);
    // params 解析出来的参数如下
    // {
    // "protocol":"http:",
    // "slashes":true,
    // "host":"localhost:3000",
    // "port":"3000",
    // "hostname":"localhost",
    // "href":"http://localhost:3000/?d=1",
    // "search":"?d=1",
    // "query":{"d":"1"},
    // "pathname":"/",
    // "path":"/?d=1"
    // }

    var options = {
        host: params.hostname,
        port: params.port || 80,
        path: params.path,
        method: settings.type
    };

    if (settings.data != null) {
        options.path += "?"
        for (var key in settings.data) {
            options.path = options.path + "&" + key + "=" + settings.data[key];
        }
        console.log(options.path);
    }

    var httpUnity = http;
    if (params.protocol == "https:") {
        options.port = 443;
        var httpUnity = https;
    }

    var req = httpUnity.request(options,function (res) {
        var data = '';
        res.on('data',function (chunk) {
            data += chunk;
        }).on('end', function () {
                if (settings.dataType === "json") {
                    try {
                        data = JSON.parse(data);
                    } catch (e) {
                        data = null;
                    }
                }
                settings.success(data);
                settings.complete(req);
            });
    }).on('error', function (e) {
            settings.error(e);
        });

// if (typeof settings.beforeSend === "function") {
// if (!settings.beforeSend(req)) {
// settings.complete(req);
// req.end();
// return false;
// }
// }

    if (settings.type === "POST") {
        var dataStr = querystring.stringify(settings.data);
        req.setHeader("Content-Length", dataStr.length);
        req.write(dataStr);
    }

    req.setTimeout(settings.timeout);
    req.end();
}

exports.ajax = ajax;

生成的Excel内容:
这里写图片描述

代码下载地址:http://download.csdn.net/detail/qxs965266509/8896431

如有转载请著名来自http://blog.csdn.net/qxs965266509

标签: 代码

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:C# 实现的 AES 加密算法

下一篇:VB.NET 人民币大小写转换代码