将数据导出到 CSV 文件 NodejS Express

sal*_*108 3 javascript csv mongoose mongodb node.js

我正在尝试将不同类型的数据从我的数据库导出到 Nodejs 和 Express 中的 CSV 文件。到目前为止,我已经尝试了几个库,但由于多种原因,似乎没有一个库能像我预期的那样工作。

我该如何解决这个问题?为了能够将我想要的所有数据导出到 CSV 文件,我应该知道什么?以及如何强制我的浏览器执行此操作?

谢谢

sal*_*108 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;
}
Run Code Online (Sandbox Code Playgroud)

现在,第二步 -导出数据: 为了导出数据,在检查了几个选项之后,我发现最方便的(对我来说)是通过 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");
Run Code Online (Sandbox Code Playgroud)

总之,我发布这篇文章是为了让其他人在使用 Nodejs 和 Express 导出 CSV 时不会像我一样陷入困境。如果您发现任何错误,或者您认为上面写的一些内容应该更彻底地解释,请告诉我,我将进行必要的更改。

亲切的问候。