Export JavaScript Data to CSV File Without Server Interaction

Export javascript data to CSV file without server interaction

There's always the HTML5 download attribute :

This attribute, if present, indicates that the author intends the
hyperlink to be used for downloading a resource so that when the user
clicks on the link they will be prompted to save it as a local file.

If the attribute has a value, the value will be used as the pre-filled
file name in the Save prompt that opens when the user clicks on the
link.

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){
A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'myFile.csv';

document.body.appendChild(a);
a.click();

FIDDLE

Tested in Chrome and Firefox, works fine in the newest versions (as of July 2013).

Works in Opera as well, but does not set the filename (as of July 2013).

Does not seem to work in IE9 (big suprise) (as of July 2013).

An overview over what browsers support the download attribute can be found Here
For non-supporting browsers, one has to set the appropriate headers on the serverside.


Apparently there is a hack for IE10 and IE11, which doesn't support the download attribute (Edge does however).

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){
A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");

if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([csvString]);
window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
}

Javascript - Download CSV as File

function downloadFile(fileName, urlData) {

var aLink = document.createElement('a');
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click");
aLink.download = fileName;
aLink.href = urlData;
aLink.dispatchEvent(evt);
}

var data = '"Column One","Column Two","Column Three"';
downloadFile('2.csv', 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data));

http://jsfiddle.net/rooseve/7bUG8/

Is there a way to download csv data from websites without using Selenium and Web Browser?

In this case I would recommend first finding the API for fetching the data. With a quick network inspection I found that the data is fetched from https://covid.cdc.gov/covid-data-tracker/COVIDData/getAjaxData?id=ed_trend_data. You can view all outgoing requests in the network tab in the developer console.

You can get the JSON data by sending a GET requests to the URL, then turn the JSON into a CSV.

import requests, csv

# Fetch data
data = requests.get("https://covid.cdc.gov/covid-data-tracker/COVIDData/getAjaxData?id=ed_trend_data").json()["ed_trend_data"]

with open("data.csv", "w") as file:

# Open CSV writer
csv_file = csv.writer(file, lineterminator='\n')

# Write heading
csv_file.writerow([ "Geography", "Date", "Syndrome", "Percent" ])

# Write data to CSV
for item in data:
csv_file.writerow([ item["Geography"], item["Date"], item["Indicator"], item["Percent"] ])

Export JSON Data to CSV File in AngularJs based on ui-grid's every row id

First convert JSON to comma separated CSV string then crate an anchor tag(a) set this CSV string as href fire a click, remove anchor tag.

function convertToCSV(array) {

var str = '';

for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','

line += array[i][index];
}

str += line + '\r\n';
}
return str;
}

function exportCSVFile(headers, items, fileTitle) {

items.unshift(headers);

var csv = convertToCSV(items);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';

var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}

/*Function to export*/
var funcExport = function (id) {

var exportHeader = ['Licence', 'Condition'];

var exportarray = [{ "Licence": "229973", "Condition": "Usage" }, { "Licence": "24141", "Condition": "Level" }];

exportCSVFile(exportHeader , exportarray, 'download' );

}

This code was taken from here

Generate CSV file from javascript under IE11

Here is the block I use to satisfy all browsers, IE 11 included and it works great for me:

if (window.navigator.msSaveBlob) {
//Internet Explorer
window.navigator.msSaveBlob(new Blob([result]), csvFileName);
} else if (window.webkitURL != null) {
//Google Chrome and Mozilla Firefox
var a = document.createElement("a");
result = encodeURIComponent(result);
a.href = "data:application/csv;charset=UTF-8," + result;
a.download = csvFileName;
a.click();
} else if (navigator.appName === "Microsoft Internet Explorer") {
//Internet Explorer 8 and 9
var oWin = window.open();
oWin.document.write("sep=,\r\n" + result);
oWin.document.close();
oWin.document.execCommand("SaveAs", true, csvFileName);
oWin.close();
} else {
//Everything Else
window.open(result);
}

Export to csv in jQuery

You can do that in the client side only, in browser that accept Data URIs:

data:application/csv;charset=utf-8,content_encoded_as_url

In your example the Data URI must be:

data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333

You can call this URI by:

  • using window.open
  • or setting the window.location
  • or by the href of an anchor
  • by adding the download attribute it will work in chrome, still have to test in IE.

To test, simply copy the URIs above and paste in your browser address bar. Or test the anchor below in a HTML page:

<a download="somedata.csv" href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Example</a>

To create the content, getting the values from the table, you can use table2CSV and do:

var data = $table.table2CSV({delivery:'value'});

$('<a></a>')
.attr('id','downloadFile')
.attr('href','data:text/csv;charset=utf8,' + encodeURIComponent(data))
.attr('download','filename.csv')
.appendTo('body');

$('#downloadFile').ready(function() {
$('#downloadFile').get(0).click();
});

Most, if not all, versions of IE don't support navigation to a data link, so a hack must be implemented, often with an iframe. Using an iFrame combined with document.execCommand('SaveAs'..), you can get similar behavior on most currently used versions of IE.



Related Topics



Leave a reply



Submit