jQuery: Convert ASP.NET GridView Data into CSV
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:
- How to search through GridView records using jQuery
- Drag and Drop GridView rows using jQuery
- Formatting ASP.NET GridView using jQuery
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.