Convert GridView Data to CSV usi
Convert GridView Data to CSV using jQuery
At times you may want to allow the end user to save GridView data into CSV
format for further processing (say for opening later in Excel). Doing so using
server side code is quite common. However, this requires an extra round trip to
the server. You can also convert data from a GridView into CSV using jQuery. The
former technique is good if you wish to present download dialog to the end user
whereas the later (jQuery) technique is good if you want to present the CSV data
on the screen so that user can copy-paste it as per his requirement. This
post discusses the later technique of converting GridView data to CSV. For an
example of the former technique read
this article.
Consider a following GridView that shows the Customers table from Northwind
database. For the sake of simplicity only first 10 records are shown.

As you can see the web form has a button to initiate the CSV conversion. The
converted CSV data is shown in a Text Area.
Let's see the jQuery code that generates the CSV data by reading it from the
GridView.
$(document).ready(function () {
$("#Button1").click(function () {
var rows = [];
var str = '';
$("#GridView1").find("tr").each(function () {
//header row
if ($(this).find("th").length) {
var headerArray = [];
$(this).find("th").each(function () {
str = $(this).text().replace(/"/g, '""');
headerArray.push('"' + str + '"');
});
rows.push(headerArray.join(','));
} else {
//data rows
var dataArray = [];
$(this).find("td").each(function () {
str = $(this).text().replace(/"/g, '""');
dataArray.push('"' + str + '"');
});
rows.push(dataArray.join(','));
}
});
var csv = rows.join('\n');
$("#TextArea1").val(csv);
});
});
The ready() function wires a click event handler to the "Show CSV Data"
button. Inside the click event handler you find all table rows (<tr> elements)
from GridView1. All the <tr> elements are found using find() method. The outer each() iterates through all the <tr> elements.
Then
all <th> (header cells) or <td> (data cells) elements are found.
Another each() iterates through all the <th> or <td> elements. The text()
function returns the text content of the corresponding <th> or <td>. If the data contains
double quote characters they are replaced by two double quotes.
The push()
method then stores the replaced text in headerArray (for <th>) or dataArray (for
<td>) respectively. The headerArray and dataArray is added to another array -
rows - by joining its elements. While joining the elements a comma is used as an
element separator. Finally, elements of rows array are joined using \n as the
element separator. This way each row of data will appear on a newline. This will give you the complete CSV data from the GridView
in a variable - csv.
The CSV data is then displayed in TextArea using val() method.