I have a JavaScript function that enables me to download a CVS file. When I open this file in excel, everything is placed in the same column instead.
This is my code:
function convertToCSV(dataArray) {
var csvContent = "data:text/csv;charset=utf-8,";
dataArray.forEach(function(infoArray, index)
{
dataString = infoArray.join(",");
csvContent += index < dataArray.length ? dataString+ "\n" : dataString;
});
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "download.csv");
document.body.appendChild(link);
link.click();
}
This is what it looks like:
This is the output I'm expecting:
What am I doing wrong? Any help would be appreciated.
NB: I have been looking for a way to export straight to an .xlsx or .xls file, but I didn't win.
You can use mongo-xlsx module to export your data to xlsx file
var mongoXlsx = require('mongo-xlsx');
var data=dataArray;
var model=mongoXlsx.buildDynamicModel(data);
mongoXlsx.mongoData2Xlsx(data, model, function(err, data) {
console.log("data",data);
console.log('File saved as:', data.fullPath);
});
Hope this helps
You could do this with native js fairly easily like so:
let text = '';
dataArray.map(arr => text += arr.join(',') + '\r\n');
let link = document.createElement('a');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + escape(text));
link.setAttribute('download', 'download.csv');
document.body.appendChild(link);
link.click();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.