2017-09-24 78 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。 如果您發現任何錯誤,或者您認爲上面所寫的一些內容應該進行更徹底的解釋,請讓我知道,我會進行必要的更改。

親切的問候。