2017-09-24 79 views
0

我试图将不同类型的数据从我的数据库导出到Nodejs中的CSV文件中并进行表达。到目前为止,我已经尝试了好几个库,看起来没有任何工作像我期望的那样有许多不同的原因。将数据导出为CSV文件NodejS Express

我该如何解决这个问题?为了能够将我想要的所有数据导出到CSV文件,我应该知道什么?和我如何强制我的浏览器做到这一点?

感谢

+0

你有没有考虑过使用mongoexport命令? https://docs.mongodb.com/manual/reference/program/mongoexport/ – DevKyle

回答

0

所以,很多的挣扎后,我将分享我的主要见解,是不是很明显给谁正在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表达出口CSV。 如果您发现任何错误,或者您认为上面所写的一些内容应该进行更彻底的解释,请让我知道,我会进行必要的更改。

亲切的问候。