Generating csv files using json data in angular 4

Posted By : Ranjan Mondal | 24-Sep-2017

Introduction :


CSV full form is comma separated values. Here data saved in the structured format.Its extension is .csv. It takes the form of the text file containing information separated by the comma.
These type of file can be used with any spread sheet program. An example is such as Microsoft Excel, Open Office Calc, or Google Spreadsheets.

These types of files generally used to exchange data especially large amount of data among different applications. Database application, analytic software and other application store huge amount of data mostly support CSV format.

We can create CSV files in the backend as well as front end.

Following is the way of creating the CSV file in the front end.

 

Step 1. In service file of angular 4,  in 2nd line, a call is made to the server for JSON data. From there we are converting it CSV files

 
 downloadCSV(itemsPerPage, skip) {
      this.UserServiceDetails.downloadCSV(this.email, 0, skip, this.kycVerified, this.mobileVerified, this.balance).subscribe(
        success => {
        //console.log("----------" + JSON.stringify(success));
            let data = success.data.list;
          //  console.log('user date' + JSON.stringify(data));
            let csvHeader = success.data.csvHeader;
            let csvData = this.ConvertToCSV(data, csvHeader);
            let blob = new Blob([csvData], { type: 'text/csv' });
            let dwldLink = document.createElement("a");
            let url= window.URL.createObjectURL(blob);
              let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
                if (isSafariBrowser) { //if Safari open in new window to save file with random filename.
                    dwldLink.setAttribute("target", "_blank");
                }
                dwldLink.setAttribute("href", url);
                dwldLink.setAttribute("download", "Enterprise.csv");
                dwldLink.style.visibility = "hidden";
                document.body.appendChild(dwldLink);
                dwldLink.click();
                document.body.removeChild(dwldLink);
        },
        error => {
            let err = JSON.parse(error._body);
            this.toasterService.pop('error', 'Error!', err.message);
        }
      );
    }
 

Above Service return JSON data like this. This is example your JSON data can be of any format. 

 
{
    "data": {
        "csvHeader": [
            "Status",
            "User Id",
            "Name",
            "Type",
            "Email",
            "Country",
            "MobileVerified",
            "Mobile Number",
            "KYC Complete",
            "Registration Date",
            "Last Login",
            "PBD",
            "Referal Check",
            "BTC Balance",
            "BTC Address",
            "ETH Balance",
            "ETH Address",
            "TOKEN Balance",
            "TOKEN Address"
        ],
        "totalCount": 32,
        "list": [
            {
                "Status": "Active",
                "MobileVerified": "No",
                "User Id": 35,
                "Email": "[email protected]",
                "TOKEN Address": "",
                "TOKEN Balance": "",
                "BTC Address": "",
                "Last Login": "",
                "Name": "ranjan mondal",
                "Registration Date": "19/09/2017",
                "Mobile Number": 342987348,
                "Type": "INDIVIDUAL",
                "PBD": "No",
                "BTC Balance": "",
                "ETH Balance": 0,
                "KYC Complete": "No",
                "Country": "Guinea-Bissau",
                "Referal Check": "No",
                "ETH Address": "0xd07c69f91e42d30198f9c9194e6fd79ad1aa672f"
            },
            {
                "Status": "Active",
                "MobileVerified": "No",
                "User Id": 34,
                "Email": "[email protected]",
                "TOKEN Address": "",
                "TOKEN Balance": "",
                "BTC Address": "",
                "Last Login": "",
                "Name": "dcscsd",
                "Registration Date": "18/09/2017",
                "Mobile Number": 9649609410,
                "Type": "CORPORATE",
                "PBD": "No",
                "BTC Balance": "",
                "ETH Balance": "",
                "KYC Complete": "No",
                "Country": "India",
                "Referal Check": "No",
                "ETH Address": ""
            }
    ]
    },
    "message": "success",
    "timestamp": 1506280388917,
    "status": 200,
    "isSuccess": true
}
 

Step 2: from above function in line  let csvData = this.ConvertToCSV(data, csvHeader); We pass the list of data and header information, and CSV files will be generated and downloaded automatically. 

 
 ConvertToCSV(objArray, headerList) {
          //console.log('convert to array called');
           var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
           var str = '';
           var row = 'S.No,';

           for (var index in headerList) { //objArray[0]
               //Now convert each value to string and comma-separated
               row += headerList[index] + ',';
           }
           row = row.slice(0, -1);
           //append Label row with line break
           str += row + '\r\n';
           for (var i = 0; i < array.length; i++) {
               var line = (i+1)+'';
               for (var index in headerList) {//array[i]
                  let head = headerList[index];

                   //if (line != '') line += ','
                   line += ',' + array[i][head];
               }
               str += line + '\r\n';
           }
           return str;
       }
 

About Author

Author Image
Ranjan Mondal

Ranjan is a bright Web App Developer, and has good knowledge of Core java, Spring and hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..