C Ernesto López: CFGRID: Export to CSV button using only Javascript

I made this little script to add to all my cfgrid ‘s a button to export to Excel without programming anything on the backend. Under normal conditions you should only copy, paste and replace the name of the grid ( gridname ) . I hope you find it useful 🙂

<script src=”js/base64.js” type=”text/javascript”></script>
<script src=”js/cfgrid2csv.js” type=”text/javascript”></script>
<button onclick=”cfgrid2csv( ‘gridName’ )” type=”button”>Excel</button>

<cfform>
<cfgrid name=”gridName” blah blah…

js/cfgrid2csv.js


function cfgrid2csv( gridName ) {
csv = ”;
items = ColdFusion.Grid.getGridObject( gridName ).getStore().data.items;
_keys = ColdFusion.Grid.getGridObject( gridName ).getStore().fields.keys

for( y=1;y<_keys.length-1;y++ )
csv += ‘”‘ + _keys[y] + ‘”,’;

csv += “\r\n”;

for( y=1;y<_keys.length-1;y++ )
csv += ‘,’;

csv += “\r\n”;

for( x=0;x<items.length;x++ ) {
for( y=1;y<_keys.length-1;y++ )
csv += ‘”‘ + items[x].data[_keys[y]] + ‘”,’;
csv += “\r\n”;
}

csv = csv.replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, ”);

var link = document.createElement(‘a’);
link.download = ‘report.csv’;
link.href = “data:text/csv;filename=report.csv;base64,” + Base64.encode( csv );
link.click();
}

Download base64.js
Download all files

C Ernesto López: CFGRID: Export to CSV button using only Javascript.