jQuery: Convert ASP.NET GridView Data into CSV

In this post, find jQuery code to convert ASP.NET GridView data into CSV format which is sometimes quite useful for exporting purpose. This can be also be done using server side code but that involves extra overhead "postback".

ASP.NET GridView control is rendered in table > th > tr > td format. The columns names are placed in th tag and all the data goes into various td tags. Also refer ebook on ASP.NET GridView & jQuery Tips and Tricks.

You may also like:

To create CSV, we need to loop through GridView including header and rows. While iterating, store the value in a array and in the end join the array with "," sign to form CSV.

$(document).ready(function() {
   $("#<%=txtCSV.ClientID%>").hide();
   $('#<%=btnSubmit.ClientID%>').click(function(e)
   {
     var arrCSV = [];
     var strTemp = '';
     $("#<%=gdRows.ClientID%>").find("tr").each(function () 
     {
       if ($(this).find("th").length) 
       {
         var arrHeader = [];
         $(this).find("th").each(function () {
           strTemp = $(this).text().replace(/"/g, '""');
           arrHeader.push('"' + strTemp + '"');
         });
       arrCSV.push(arrHeader.join(','));
      }
      else 
      {
        var arrData = [];
        $(this).find("td").each(function () {
         strTemp = $(this).text().replace(/"/g, '""');
         arrData.push('"' + strTemp + '"');
       });
       arrCSV.push(arrData.join(','));
      }
   });

    var strCSV = arrCSV.join('n');
    $("#<%=txtCSV.ClientID%>").val(strCSV);
    $("#<%=txtCSV.ClientID%>").show();
    e.preventDefault();
   });
});

If you don't want to include headers in your CSV, then you can remove below code block from above code.

if ($(this).find("th").length) 
{
   var arrHeader = [];
   $(this).find("th").each(function () {
     strTemp = $(this).text().replace(/"/g, '""');
     arrHeader.push('"' + strTemp + '"');
   });
   arrCSV.push(arrHeader.join(','));
}

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...