Export Data in CSV using JavaScript in Salesforce Lightning

Recently while working on a lightning community, we came across a use case of exporting tabular data in CSV. We were looking for a solution, which is (prioritized top to bottom):

  1. Cost-effective
  2. Quicker to achieve
  3. Good in performance with a large data set

No rocket science. Java script helped us. The reason, why we opted for JavaScript is:

  1. We already had data queried in the lightning component. Why build another solution to fetch the same data to download?
  2. Creating another VisualForce page was time and cost consuming.
  3. Maintaining columns and filter mapping between the original lightning component and the VF page could be challenging in the future.

Here is a sample code. FYI – Code is based on lightning component:

Method for Framing CSV Data:

convertArrayOfObjectsToCSV : function(component,objectRecords){ 

       // declare variables
       var csvStringResult, counter, keys, columnDivider, lineDivider; 

       // check if "objectRecords" parameter is null, then return from function 
       if (objectRecords == null || !objectRecords.length) { 
           return null; 
       } 

       // store ,[comma] in columnDivider variabel for sparate CSV values and  
       // for start next line use '\n' [new line] in lineDivider varaible   
        columnDivider = ','; 
        lineDivider = '\n'; 
     
       // in the keys store fields API Names as a key  
       keys = ['FirstName','LastName','Phone'];
  
        //this labels use in CSV file header. Put them in same sequence as API Names 
       var keyLabel = ['First Name', 'Last Name', 'Phone Number']; 
        csvStringResult = ''; 
        csvStringResult += keyLabel.join(columnDivider); 
        csvStringResult += lineDivider; 
        for(var i=0; i < objectRecords.length; i++){  
           counter = 0; 
            for(var sTempkey in keys) { 
               var skey = keys[sTempkey] ;  

               // add , [comma] after every String value [except first] 
                if(counter > 0){  
                    csvStringResult += columnDivider;  
               }    

               if(!$A.util.isUndefined(objectRecords[i][skey]) && !$A.util.isEmpty(objectRecords[i][skey])) { 
                    csvStringResult += '"'+ objectRecords[i][skey]+'"'; 
               } 

               else { 
                    csvStringResult += '"'+' '+'"'; 
               } 

               counter++; 

           } // inner for loop close  
            csvStringResult += lineDivider; 
       }// outer main for loop close  

       // return the CSV formate String  

       return csvStringResult;         
} 

Method for Downloading CSV Data:

downloadCsv : function(component,event,helper){  
       // get the Records [contact] list from 'ListOfContact' attribute    

       var stockData = component.get("v.lstOfContact");  

       // call the helper function which "return" the CSV data as a String      
       var csv = helper.convertArrayOfObjectsToCSV(component,stockData);      
       if (csv == null){return;}   

 //this code works for chrome but not for other browsers like IE or Edge 
        var csvFile = new Blob(["\ufeff",csv]); 
        var downloadLink = document.createElement("a"); 
        downloadLink.download = 'contacts.csv'; // CSV file Name* you can change it. [only name not .csv] 
        downloadLink.href = window.URL.createObjectURL(csvFile); 
        downloadLink.style.display = "none"; 
        downloadLink.target = '_blank';  
        document.body.appendChild(downloadLink); 
        downloadLink.click(); // using click() js function to trigger download csv file
}

Hope you find it useful.

#HappyCoding #HappyLightning