twitter pt IV

Just got my 2nd follower: Toxicosmica(!)

I don’t know who she is, but I guess it’s hard to personally know all your fans when you get to this level of fame.

Image

Advertisements

Exporting data from a web browser to a csv file using javascript.

If you want to skip all this text and just download a working example, go ahead and scroll to the end of this post. Otherwise, read on.


There is a comprehensive answer from Terry Young on Stack Overflow with accompanying fiddle here.

Works as you’d expect on Firefox 20 and Google Chrome 26. The file exports fine in Safari 6.0.5 but won’t name the file. Instead, it’ll save your file as ‘unknown’ (no file extension) so you’ll need to go in and rename it yourself if you’re constrained to Safari.

And then there’s this answer on Stack Overflow by adeneo. It’s a little less comprehensive but equally helpful depending on what you’re looking for. Here’s the fiddle. A rough idea of what the code looks like is shown below.

var A = [['n','sqrt(n)']];  // initialize array of rows with header row as 1st item
	 
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(','));   // unquoted CSV row
}
var csvString = csvRows.join('\n');

var a = document.createElement('a');
a.href     = 'data:attachment/csv,' + csvString;
a.target   ='_blank';
a.download = 'myFile.csv,' + encodeURIComponent(csvString); ;
a.innerHTML = "Click me to download the file.";
document.body.appendChild(a);

Finally, here’s a link to a downloadable gist on GitHub if you want to just get up and running straight away. It’s based on Terry Young‘s answer but modified to include table headers, and refactored so anything that gets done more than once gets its own function.

Listing all files in a folder [java]

From here.

public File[] listf(String directoryName) {

    // .............list file
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles(); 

    for (File file : fList) {
        if (file.isFile()) {
            System.out.println(file.getAbsolutePath());
        } else if (file.isDirectory()) {
            listf(file.getAbsolutePath());
        }
    }
    System.out.println(fList);
    return fList;
}