Generate CSV Data URI from a table via javascript

Sometimes happens to export data from table in other format like XML or CSV. In this easy tutorial, we can see how to export data from table into CSV on client side using data stored into an HTML table.

The problem

Assuming we have a table like the one below:

First Name Last Name Phone Number Email Web Site Export
Diego La Monica +39 333 7235382 [x]
Joe Average +12 345 67890 [ ]

In the above HTML table we have a list of columns relative to data extracted from a hypotetic Database Table named contacts where the last column should be a check box that allow user to choose the items to export in CSV.

The solution

Using jQuery and the following code snippet you will be able to do what you need easily and without having to ask the server to process the request again.

Note: This solution requires that your browser supports the data URI scheme.

Dependencies: this script requires jQuery to work.

function table2CSV(){
	var dataURL = '',
		fieldSeparator = ';',
		textField = '"',
		lineSeparator = '\n',
		regExpTesto = /(")/g,
		regExp = /[";]/;
	$('#orders_list tr').each( function(){
		var dataRow = '';
		if($('input:checkbox', this).is(':checked') || $(this).is(':first-child')){
			$('td', this).not(':last').each( function(){
				var value = $(this).text();
				if(dataRow!='') dataRow += fieldSeparator;
					value = textField + value.replace(regExpTesto, '$1$1') + textField;
				dataRow += value;
			if(dataURL != '') dataURL += lineSeparator;
			dataURL += dataRow;
	window.location.href = 'data:text/csv;charset=utf-8;base64,' + btoa(dataURL);

What is a data URI scheme?

The data URI scheme is a URI scheme that provides a way to include data in-line in web pages as if they were external resources. This technique allows normally separate elements such as images and style sheets to be fetched in a single HTTP request rather than multiple HTTP requests, which can be more efficient.

In browsers that fully support Data URIs for “navigation”, JavaScript-generated content can be provided as file “download” to the user, simply by setting window location.href to a Data URI. (from Wikipedia)

To build a data URI you must produce a string such as:

data:<content-type>;charset=<encoding>;base64,<base64 content>

Providing the data in base64 format is not mandatory, so you can build the data URI as a  plain buffer. But remember that you need to encode the generated string with the encodeURIComponent javascript method because you are building a URI. For this reason, and the data URI the could be as follow:

data:<content-type>;charset=<encoding>,<encoded URI content>

Which browser supports data URI?

Most Browser support Data URIs. However, Internet Explorer 7 (damn it!!!) does not. Internet Explorer 8 has slightly better support, but with some limitations like the elements that accepts data URI format and the size of the data URI being limited to 32Kb. In Internet Explorer 9 the 32Kb size limitation has been removed.

Why the downloaded file has a strange (random) name?

Due the data URI implementation, you don’t have a filename for the object you are trying to download, so the browser gives to the user a “friendly” name to the file you’re asking for. However if the browser supports the download attribute and the data URI is written in the href of an HTML link tag (<a />) you can use it to give a real friendly name to the file.

Live demo

Here some ready to use examples

  1. Base example
  2. Download file with given name (if browser supports it)

2014-11-03 – UPDATE: For some strange behavior jsfiddle does not show the latest revision of the code (for the 2nd example). Now it has explicitly mentioned in the link.

2014-11-03 – UPDATE 2: I was making some errors in using jsFiddle. Now both links are right. You can use the following soundtrack while reading this update ( “…Come on baby light me (with) fire!” :) )

Just few words for the reader

You can use this code both in commercial and open source projects without any obbligation And, if you liked this article, please spent few seconds to share it on Twitter, Facebook, Google+, LinekdIn or leave a comment to tell me what do you think.

If you think I’m an interesting person you can keep in touch on Twitter.

2014-11-03 UPDATE 3: Thanks to Russ for some grammar suggestion :)




%d blogger hanno fatto clic su Mi Piace per questo: