DBからNodejsのCSVファイルにさまざまな種類のデータをエクスポートしようとしています。私はこれまでにいくつかのライブラリを試してきました。CSVファイルへのデータのエクスポートNodejS Express
どうすればこの問題を解決できますか?私がCSVファイルにしたいすべてのデータをエクスポートできるようにするにはどうすればよいでしょうか?どのようにブラウザに強制することができますか?
おかげ
DBからNodejsのCSVファイルにさまざまな種類のデータをエクスポートしようとしています。私はこれまでにいくつかのライブラリを試してきました。CSVファイルへのデータのエクスポートNodejS Express
どうすればこの問題を解決できますか?私がCSVファイルにしたいすべてのデータをエクスポートできるようにするにはどうすればよいでしょうか?どのようにブラウザに強制することができますか?
おかげ
だから、苦労をたくさんした後、私はWeb開発に彼らの最初のステップを作っている人にその明白ではありません、私のメインの洞察を、共有します。
CSVへのエクスポートは、主に2つのステップに分けられます。 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として解析させることでした。それはnodejsとExpressを使用して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");
、 :私は次のコードで作られています。 エラーが見つかった場合、または上記の書類の一部をより完全に説明する必要があると思われる場合は、私にお知らせください。必要な変更を行います。
親切にしてください。
mongoexportコマンドの使用を検討しましたか? https://docs.mongodb.com/manual/reference/program/mongoexport/ – DevKyle