Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have "Export as CSV" button in Chrome Extension?

I created a Chrome extension which scans the page and creates a list of h1-h6 tags of a current page in a popup window. This is how this list looks like for main StackOverflow page:

h1 | All Questions
h3 | XmlElement has a list as attribute but its items aren't separated by comma
h3 | Eclipse, Easily remove/fix all @Override due to Java version change
...

I'd like to have an "Export" button, which would give me an ability to save this report in CSV format. Is it possible?

like image 231
DNNX Avatar asked Jan 03 '12 14:01

DNNX


People also ask

How do I export HTML table data as .CSV file?

HTML Code. The members HTML table contains some basic users data, like name, email, country. On clicking the button, exportTableToCSV() method is called to export table data to CSV file. Also, the desired filename for download CSV file is passed to this function.

How do I export a CSV file from a website?

There is no simple solution to export a website to a CSV file. The only way to achieve this is by using a web scraping setup and some automation. A web crawling setup will have to be programmed to visit the source websites, fetch the required data from the sites and save it to a dump file.

What is CSV extraction?

Most often understood as an acronym for “comma-separated values” (though sometimes called “character-separated values” because the separator character does not have to be a comma), CSV is a file format that stores tabular data in plain-text form.


2 Answers

You can use data URI scheme to create a URI storing the CSV content. Then you can create a A element with a download attribute set to the desired file name.

If your CSV is really big, you should use BlobBuilder and webkitURL.createObjectURL instead of data URI scheme to create the link href.

Here is an example using data URI scheme:

var link = document.createElement("a");
link.textContent = "Save as CSV";
link.download = "file.csv";
link.href = "data:text/csv,h1;All Questions\n"
document.body.appendChild(link);

When the user will click the link, the "file.csv" will be automatically saved in the default Download folder.

like image 83
check_ca Avatar answered Sep 22 '22 22:09

check_ca


Based on @check_ca answer, I've coded the following to return a csv link element for array data:

function getCSVLinkElement(arr){

    var link = document.createElement("a");
    link.textContent = "Save as CSV";
    link.download = "file.csv";
    var csv = arr.map(function(v){return v.join(',')}).join('\n');
    link.href = encodeURI("data:text/csv,"+csv);

    return link;

}

var el = getCSVLinkElement([['num','sq'],[2,4],[3,9]]);
document.body.appendChild(el);
like image 45
Ehsan88 Avatar answered Sep 20 '22 22:09

Ehsan88