Ticker

6/recent/ticker-posts

Download Data as CSV File In Salesforce Lightning Component

 







Apex Controller [csvDownloadFile.apxc]

public class csvDownloadFile {
@AuraEnabled
   public static list <contact> fetchContactRecord(){
      
      List <contact> returnConList = new List < contact > ();
        
      for(contact con: [SELECT firstName, LastName, Department, MobilePhone From contact LIMIT 500]) {
             returnConList.add(con);
          }
         return returnConList;
   }
}


Lightning Component [csvFile.cmp]

<aura:component controller="csvDownloadFile">          
<!--aura init handler , call js "loadContactList" function on component load, and display contact data on table--> <aura:handler name="init" value="{!this}" action="{!c.loadContactList}"/> <!--Declare Attribute for store Contact Records List-->
<aura:attribute name="ListOfContact" type="contact[]"/> <!--Use "slds-m-around- -xx-large" class to add standard Large padding to the component--> <div class="slds-m-around--xx-large"> <button class="slds-button slds-button--brand" onclick="{!c.downloadCsv}">Download As CSV</button> <br/><br/> <!--HTML tabel for Contact Records display--> <table class="slds-table slds-table--bordered slds-table--cell-buffer"> <thead> <tr class="slds-text-title--caps"> <th class="slds-is-sortable slds-text-title--caps" scope="col"> <span class="slds-truncate" title="Name">First Name</span> </th> <th class="slds-is-sortable slds-text-title--caps" scope="col"> <span class="slds-truncate" title="Last Name">Last Name</span> </th> <th class="slds-is-sortable slds-text-title--caps" scope="col"> <span class="slds-truncate" title="Department">Department</span> </th> <th scope="col"> <div class="slds-truncate" title="MobilePhone">Mobile Phone</div> </th> </tr> </thead> <!--table body start, Iterate contact list as a <tr> --> <tbody> <aura:iteration items="{!v.ListOfContact}" var="con"> <tr> <th scope="row"> <div class="slds-truncate" title="{!con.FirstName}">{!con.FirstName}</div> </th> <th scope="row"> <div class="slds-truncate" title="{!con.LastName}">{!con.LastName}</div> </th> <th scope="row"> <div class="slds-truncate" title="{!con.Department}">{!con.Department}</div> </th> <th scope="row"> <div class="slds-truncate" title="{!con.MobilePhone}">{!con.MobilePhone}</div> </th> </tr> </aura:iteration> </tbody> </table> </div> </aura:component>


JavaScript Controller [csvFileController.js]

({
    // ## function call on component load  
    loadContactList: function(component, event, helper){
       helper.onLoad(component, event);
    },
    
    // ## function call on Click on the "Download As CSV" Button. 
    downloadCsv : function(component,event,helper){
        
        // get the Records [contact] list from 'ListOfContact' attribute 
        var stockData = component.get("v.ListOfContact");
        
        // call the helper function which "return" the CSV data as a String   
        var csv = helper.convertArrayOfObjectsToCSV(component,stockData);   
         if (csv == null){return;} 
        
        // ####--code for create a temp. <a> html tag [link tag] for download the CSV file--####     
	     var hiddenElement = document.createElement('a');
          hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
          hiddenElement.target = '_self';
          hiddenElement.download = 'ExportData.csv';  // CSV file Name* you can change it.[only name not .csv] 
          document.body.appendChild(hiddenElement); // Required for FireFox browser
    	  hiddenElement.click(); // using click() js function to download csv file
        }, 
 })


JavaScript Helper [csvFileHelper.js]

({
   onLoad: function(component, event) {
      //call apex class method
      var action = component.get('c.fetchContactRecord');
      action.setCallback(this, function(response){
         //store state of response
         var state = response.getState();
         if (state === "SUCCESS") {
            //set response value in ListOfContact attribute on component.
            component.set('v.ListOfContact', response.getReturnValue());
         }
      });
      $A.enqueueAction(action);
   },
    
   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 valirable store fields API Names as a key 
        // this labels use in CSV file header  
        keys = ['FirstName','LastName','Department','MobilePhone','Id' ];
        
        csvStringResult = '';
        csvStringResult += keys.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; 
                   }   
               
               csvStringResult += '"'+ objectRecords[i][skey]+'"'; 
               
               counter++;
 
            } // inner for loop close 
             csvStringResult += lineDivider;
          }// outer main for loop close 
       
       // return the CSV formate String 
        return csvStringResult;        
    },
})


Note-: If You want to add another column to the CSV file from the object, add the Field API name to Highlighted Red Line on the JS helper controller. such as -:


keys = ['FirstName','LastName','Department','MobilePhone','Id','CustomFieldApiName__c' ];

TestCSVApp.app
<aura:application extends="force:slds">
    <c:csvFile />
</aura:application>





Post a Comment

0 Comments