views:

210

answers:

1

What's the easiest/fastest way to grab data out of a YUI DataTable and turn it into a single CSV or TSV string? I basically just want to implement a one-click way to get the entire DataTable (it should preserve the currently-applied sorting) into a form that users can paste into a spreadsheet.

My DataTable can get pretty big - 5000 to 10000 rows, 5 to 10 columns - so efficiency does matter.

+2  A: 

How about something like this:

function dataTableAsCSV (myDataTable) {

    var i, j, oData, newWin = window.open(),
        aRecs = myDataTable.getRecordSet().getRecords(),
        aCols = myDataTable.getColumnSet().keys;

    newWin.document.write("<pre>");

    for (i=0; i<aRecs.length; i++) {
        oData = aRecs[i].getData();

        for (j=0; j<aCols.length; j++) {
            newWin.document.write( oData[aCols[j].key] + "\t");

        }
        newWin.document.write("\n");

    }

    newWin.document.write("</pre>n");
    newWin.document.close();
}

It will render the data table content as TSV into a new window. It doesn't handle data with tabs in it, but that would just be some extra substitutions on oData[aCols[j].key].

Gavin Brock
You know, I'm surprised at how quick that is.
Matt Ball
...And it preserves sorting. Awesome!
Matt Ball