Export JSON to CSV using JQuery/Javascript and Bootstrap in ASP.NET

watch_later 6/24/2019
This article gives an explanation about how to export JSON string to CSV file in asp.net using jquery/javascript and bootstrap 4 as well as also explains how to parse JSON string in an object and how to save CSV file using Jquery in asp.net and explains how to create an element using Jquery.

In our previous articles, we learned Export JSON Data to Excel/CSV File using AngularJs With Bootstrap and Read CSV File In ASP.NET With Example C# and VB.NET as well as Export Dataset/Datatable to CSV File Using C# and VB.NET and AngularJS Pie Chart Using Highcharts Library With Example using Javascript, So in this article, we will learn about Export JSON Data to CSV File using Jquery or Javascript.

Export JSON to CSV using JQuery/Javascript and Bootstrap in ASP.NET

Many of developers those who work with the web applications will have at least heard talk about the export JSON data to CSV file for reporting functionality. They many times get such requirement for the export report in CSV file directly from a JSON string and many of them write code for export JSON string to CSV using c#, vb.net, Java, PHP, and many other programmings languages but you have to take care of the performance of your application also so if you write the same code to export JSON string to CSV at client side using Jquery or Javascript then you can somehow improve the performance of your web application because all your code run at client side, So in this article I'll show how to write a script for export JSON string to CSV using Jquery in asp.net using bootstrap.

Requirement


1) Export JSON string to CSV using JQuery/Javascript and Bootstrap in ASP.NET
2) All required validations should be work properly.
3) User should be able to enter the name of the CSV report.
4) User should be able to download the CSV file.

Implementation


So, let's start implementation for export JSON data to CSV, and for that, you have to follow some steps described below.

Step 1: create a new web project in visual studio and add new web forms with file extension .aspx.

Step 2: Now you have to give the title of web forms, metatag meta viewport and link bootstrap CDN CSS and javascript with created asp.net web forms for the apply bootstrap class to aspx controls for better user interface before end <head> tag.
<title>Export JSON to CSV in ASP.NET using Javascript and Bootstrap 4</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
Step 3: Now you have to design web forms with one simple textbox to getting the name of CSV report from the user as input and one multiline textbox for getting JSON string as an input from the user as well as a simple button to convert JSON data to CSV and download the generated report in CSV format.

To design your asp.net web forms you have to write following code in between <body> tag start and end.
<form id="form1" runat="server">
        <div class="container">
            <center>
    <h2 >JSON to CSV</h2>
   </center>
            <div class="row">
                ReportName:
                <asp:TextBox ID="txtReportName" CssClass='form-control' runat="server"></asp:TextBox>
            </div>
            <br />
            <div class="row">
                JSON String:
                <asp:TextBox ID="txtJson" CssClass='form-control' TextMode="MultiLine" Height="170" runat="server"></asp:TextBox>
            </div>
            <br />
            <div>
                <asp:Button ID="btnCSV" CssClass='form-control btn btn-primary' runat="server" Text="Convert to CSV" />
            </div>
        </div>
    </form>
Step 4: Now, you have to write a following Jquery/Javascript to convert JSON to CSV before end <body> tag and after end <form> tag.
<script type="text/javascript">
        $(document).ready(function () {
            $('#btnCSV').click(function () {
                var JsonData = $('#txtJson').val();
                var ReportName = $('#txtReportName').val();
                if (ReportName == '') {
                    alert("Report Name should not Empty, Please Enter Report Name.");
                    return;
                }
                if (JsonData == '') {
                    alert("JSON string Should not Empty, Please Enter JSON String.");
                    return;
                }
 
                Export_JSON_to_CSV(JsonData, ReportName, true);
            });
        });
 
        function Export_JSON_to_CSV(JSONString, ReportName, isShowHeader) {
            var arrJsonData = typeof JSONString != 'object' ? JSON.parse(JSONString) : JSONString;
            var CSV = '';
            CSV += ReportName + '\r\n\n';
            if (isShowHeader) {
                var row = "";
                for (var index in arrJsonData[0]) {
                    row += index + ',';
                }
                row = row.slice(0, -1);
                CSV += row + '\r\n';
            }
            for (var i = 0; i < arrJsonData.length; i++) {
                var row = "";
                for (var index in arrJsonData[i]) {
                    row += '"' + arrJsonData[i][index] + '",';
                }
                row.slice(0, row.length - 1);
                CSV += row + '\r\n';
            }
            if (CSV == '') {
                alert("Invalid JsonData");
                return;
            }
            var fileName = "CSV_";
            fileName += ReportName.replace(/ /g"_");
            var uri = 'Data:text/csv;charset=utf-8,' + escape(CSV);
            var link = document.createElement("a");
            link.href = uri;
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
 
        </script>

Explanation


As you can see in the script above there we have created a jquery function and click of a btnCSV button and getting a JSON string as input from a txtJson multiline textbox and store in the local variable called JsonData. Same as we getting the name of a report from textbox txtReportName as input and storing in the local variable called ReportName. finally, we checked if the value of variable JsonData or ReportName is blank or empty then we show the alert message to the user and return.

If all validations process complete successfully then we called a function Export_JSON_to_CSV with 3 different arguments JsonData, ReportName, and isShowHeader where JsonData indicates the JSON string, ReportName indicates the name of report and isShowHeader is boolean and indicates is display headers in CSV file or not.

In the Export_JSON_to_CSV function first, we checked JSONString is an object or not If JSONString is not an object then we will parse JSON string using JSON.parse and parse the JSON string in an Object and stored the result in the variable arrJsonData.

Now, To display the title of the report in the first line of CSV file we taken a local variable called CSV and concated the ReportName with this variable and also concated a \r\n\n for the line break. Now, we checked the condition for a condition for header creation where we checked the flag isShowHeader is true then will generate the Header else not. If the flag is true then thought a loop we will extract the header from the 1st index of a JSON array and then convert each and every value to string and the comma-separated and finally append header row with a line break. Now, we have used the 2nd loop to extract each column and convert it in the comma-separated string and finally adds a line break after each and every row.

Then we generated a filename with expention.csv and Initialized the file format csv and creates URI. Then we generate a temp anchor <a/> tag and created a link using URI and set the visibility hidden so it will not effect on your web-layout, and finally append created anchor tag with body and then performed a automatic click using link.click() on the link and remove it after an automatic click.

Step 5: Run project in a web browser.

Step 6: Give the user inputs JSON string and name of report and clicks on a button called Convert to CSV.

Sample JSON string

[{"EmpId": 1001,"EmployeeName": "Nikunj Stasiya","Department": "Information Technology","Designation": "Sr.Software Engineer","City": "Surat, India","ContactNo": "9*******24"},{"EmpId": 1002,"EmployeeName": "Hiren Dobariya","Department": "Information Technology","Designation": "Sr.Software Engineer","City": "Rajkot, India","ContactNo": "8*******96"},{"EmpId": 1003,"EmployeeName": "Vivek Ghadiya","Department": "Information Technology","Designation": "Web Developer","City": "Jamnagar, India","ContactNo": "7*******98"},{"EmpId": 1004,"EmployeeName": "Milan lathiya","Department": "Information Technology","Designation": "Android Application Developer","City": "Surat, India","ContactNo": "8*******77"},{"EmpId": 1005,"EmployeeName": "Kishan Kotadiya","Department": "Information Technology","Designation": "Web Developer","City": "Surat, India","ContactNo": "7*******53"},{"EmpId": 1006,"EmployeeName": "Sarah Demola","Department": "Information Technology","Designation": "Software Engineer","City": "California, USA","ContactNo": "7*******22"}]

Step 7: Done.

Output

Export JSON to CSV

CSV File

You may like to read



Summary


In this article, we learned how to convert JSON string to comma-separated CSV file using JQuery/Javascript in ASP.NET web forms.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon