将数据导出为CSV文件Node.js Express

3
我正在尝试从我的数据库中以Nodejs和Express为基础将不同类型的数据导出到CSV文件。到目前为止,我已经尝试了几个库,但由于各种原因,似乎没有一个能像我期望的那样工作。
我应该怎么解决这个问题?为了能够将我想要的全部数据导出到CSV文件,我应该掌握什么知识?我该如何强制浏览器执行此操作?
感谢您的帮助。

你考虑过使用mongoexport命令吗?https://docs.mongodb.com/manual/reference/program/mongoexport/ - DevKyle
1个回答

5
所以,经过了很多努力,我将分享一些对于刚开始学习Web开发的人来说不是那么明显的主要见解。
导出到CSV可以分为两个主要步骤: 1. 将您的数据排列成CSV结构/模型。 2. 导出数据/使其在客户端下载。
所以我会逐步解释。 第一步 - 将您的数据排列成CSV结构/模型: 要将您的数据放入CSV结构中,最有可能的方法是找到一个库,将您想要导出的数据取出并格式化为CSV。 如果您的数据模型像我的一样复杂,您将不得不创建一个自定义函数。无论哪种方式,都不应该太复杂。 以下是我使用的一个例子:
// The function gets a list of objects ('dataList' arg), each one would be a single row in the future-to-be CSV file
// The headers to the columns would be sent in an array ('headers' args). It is taken as the second arg
function dataToCSV(dataList,headers){
    var allObjects = [];
    // Pushing the headers, as the first arr in the 2-dimensional array 'allObjects' would be the first row
    allObjects.push(headers);

    //Now iterating through the list and build up an array that contains the data of every object in the list, in the same order of the headers
    dataList.forEach(function(object){
        var arr = [];
        arr.push(object.id);
        arr.push(object.term);
        arr.push(object.Date);

        // Adding the array as additional element to the 2-dimensional array. It will evantually be converted to a single row
        allObjects.push(arr)
    });

   // Initializing the output in a new variable 'csvContent'
    var csvContent = "";

    // The code below takes two-dimensional array and converts it to be strctured as CSV
    // *** It can be taken apart from the function, if all you need is to convert an array to CSV
    allObjects.forEach(function(infoArray, index){
      var dataString = infoArray.join(",");
      csvContent += index < allObjects.length ? dataString+ "\n" : dataString;
    }); 

    // Returning the CSV output
    return csvContent;
}

现在,第二步 - 导出数据: 为了导出数据,在考虑了几个选项后,我发现最方便的方法(对我来说)是通过HTTP头发送数据,并使浏览器将其作为CSV文件下载和解析。我使用以下代码实现了这一点:

//this statement tells the browser what type of data is supposed to download and force it to download
    res.writeHead(200, {
        'Content-Type': 'text/csv',
        'Content-Disposition': 'attachment; filename=*custom_name*.csv'
    });
// whereas this part is in charge of telling what data should be parsed and be downloaded
    res.end(dataToCSV(dataList,["ID","Name","Date"]),"binary");

总之,我写这篇文章是为了让其他人在使用nodejs和express导出CSV时不会像我一样遇到困难。如果您发现任何错误或认为上述内容应该更详细地解释,请告诉我,我会做出必要的更改。
此致敬礼。

下一步很简单:根据你请求文件的方式,你可能还需要下载响应。你可以使用这个包:https://github.com/kennethjiang/js-file-download或者直接查看源代码并自己编写(只有30行而已)。 - blakeface
今天我也曾经和你一样,非常感谢你提供这么详细的答案。 - George Linardis
1
@sale108,如果数据量很大会发生什么情况? - user1149244
@user1149244 - 那时候不需要它。显然如果它太大以至于无法放入内存,你将需要使用其他方法(可能是流式传输),然后在接收端重新组装。 - sale108

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接