【问题标题】:How to store Javascript array elements in excel file while converting JSON object to excel file in node js?如何在节点js中将JSON对象转换为excel文件时将Javascript数组元素存储在excel文件中?
【发布时间】:2019-12-27 22:19:57
【问题描述】:

我有一个用例,我需要将用户数据导出到 excel 文件中。用户模型(mongo db 模型)包含array 类型的字段。导出时,每个字段都存储到 excel 文件中,除了该数组字段数据。如何将该数组数据作为逗号分隔值存储到 excel 文件中?

这是我的代码:

var XLSX = require('xlsx');

exportCustomerDataToExcel: async function(customerId){
    let err,customerData;

    [err, customerData]=await to(Customer.find({"_id":customerId},'name email phone unit block communityAccountNo status').lean().exec());

    //*name email phone unit block communityAccountNo status* are fields of customer & unit is an array

    if(err) {TE(err, true)};

    if(!customerData || customerData.length==0) return false;

    if(customerData){
        customerData.map(function(elem) {
            if (elem._id) delete elem._id

        });
        var newWB=XLSX.utils.book_new();
        var newWS=XLSX.utils.json_to_sheet(customerData);
        XLSX.utils.book_append_sheet(newWB, newWS,"Customers");
        [err,excelWB]=await to(this.writeFileQ(newWB, "./public/exports/"+customerId+".xlsx"));
        if(err) TE(err, true);
        return ({file:customerId+".xlsx"});
    }
},

writeFileQ: function(workbook, filename) {
    return new Promise((resolve, reject) => {
        XLSX.writeFileAsync(filename, workbook, (error, result) => {
          (error)? reject(error) : resolve(result);
        });
    });
}

示例代码是:

{
    "name" : "Some Name",
    "email" : "SomeName@gmail.com",
    "phone" : "94XXXXXXXX",
    "communityAccountNo" : "ABCD1234",
    "status" : true,
    "block" : "1",
    "unit" : [ 
        "9-2", 
        "9-3"
    ]
}

这是我得到的excel:

我想在 unit 标签下将单元元素存储为 9-2,9-3。有可能吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose xlsx


    【解决方案1】:

    您应该在创建 excel 文件之前将数组重新格式化为字符串,以使其按您想要的方式工作。您可以通过使用数组join 方法来实现这一点,并使用, 作为参数。像这样的:

    customerData.unit = customerData.unit.join(',');
    

    甚至customerData.unit = customerData.unit.join();,因为,是默认参数。

    然后创建您的 Excel 工作表。

    【讨论】:

    • 当我尝试更新 excel 文件并导入时,您知道如何将它们作为数组存储在数据库中吗?例如,我会更新单元并上传,它将作为数组存储在数据库中。有可能吗?
    • 这取决于数据库,如果您使用的是 MongoDB,则将数组推送到集合中不会有任何问题。如果您使用的是 MySQL,则效率不高。但是你可以使用 JSON SQL 类型来存储数组
    猜你喜欢
    • 2020-01-19
    • 1970-01-01
    • 2018-07-05
    • 2014-10-31
    • 2015-04-01
    • 2023-02-14
    • 2016-12-18
    • 2023-01-19
    • 2018-10-13
    相关资源
    最近更新 更多