How do I download data as csv?

I have read data from SQL and want to download it as csv.

Quoting response from Hetu:

{{
function() {
    const csvRows = AllDataQuery.data;
    const objArr = [];
    const headers = csvRows[0].split(',');
        for(let i = 1; i < csvRows.length; i++) {
            const rowObj = {};
            objArr.push(rowObj);
            const rowArr = csvRows[i].split(',');
            rowArr.forEach((val, index) => {
                rowObj[headers[index]] = val;
            });
        }
    download(objArr, "AllData.csv", "data:text/csv")
}()
}}
1 Like

There is also a download button available with table widget which can be used to download data as a csv or excel sheet.

This code is not working at all, it makes an array, but not a csv…

here is the working code:

{{
function(){
	var json = sql_query.data;
	var fields = Object.keys(json[0]);
	var csv = json.map(function(row){
		return fields.map(function(fieldName){
			return JSON.stringify(row[fieldName])
		}).join(',')
	});
	
	csv.unshift(fields.join(',')); 
	csv = csv.join(String.fromCharCode(10));
	download(csv, "AllData.csv", "data:text/csv");
}()
}}

I really don’t know why I was forced to use String.fromCharCode(10) and not \n, but otherwise it was giving me an error.