Hello friends. In this post you will find a code example that helps you to download/export salesforce object data in csv file. so let's get started,
Export data in csv file in lightning component
To implement this example, I am using account sobject but you can pick any salesforce object as per your need.
ExportDataInCSVHandler.apxc
public class ExportDataInCSVHandler {ExportDataInCSV.cmp
@AuraEnabled(cacheable=true)
public static List<Account> getAccountList() {
return [SELECT Id, Name, Type, Rating, Phone, Website, AnnualRevenue FROM Account order by name asc];
}
}
<aura:component controller="ExportDataInCSVHandler" implements="flexipage:availableForAllPageTypes" access="global">ExportDataInCSVController.js
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="acclist" type="Account[]"/>
<aura:attribute name="exportWithId" type="boolean" default="false"/>
<div style="width:100%;padding: 15px">
<div style="float:left">
<lightning:input type="toggle" aura:id="tglbtn" label="Export With Id" onchange="{!c.btnToggleButton}" messageToggleActive="" messageToggleInactive="" />
</div>
<div style="float:right">
<lightning:button iconName="utility:download" iconPosition="left" label="Download Account" onclick="{!c.downloadSelectedCase}" class="slds-button slds-button_brand"/>
</div>
</div>
<br/><br/>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<thead>
<tr>
<th scope="col">
<div class="slds-truncate" title="">Sr. No.</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Account Name">Account Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Type">Type</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Rating">Rating</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Phone">Phone</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Website">Website</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.acclist}" var="a" indexVar="icount">
<tr>
<td scope="row">
{!icount+1}
</td>
<td scope="row">
{!a.Name}
</td>
<td scope="row">
{!a.Type}
</td>
<td scope="row">
{!a.Rating}
</td>
<td scope="row">
{!a.Phone}
</td>
<td scope="row">
{!a.Website}
</td>
</tr>
</aura:iteration>
</tbody>
</table>
</aura:component>
({ExportDataInCSVHelper.js
doInit : function (component, event, helper) {
helper.getAccountData(component);
},
downloadSelectedCase :function(component, event, helper){
var recordsList=component.get("v.acclist");
var csv = helper.convertListToCSV(component, recordsList);
if (csv == null){return;}
// Create a temporal <a> html tag to download the CSV file
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_self';
hiddenElement.download ='AccountExportData.csv';;
document.body.appendChild(hiddenElement);
// using click() js function to download csv file
hiddenElement.click();
},
btnToggleButton:function(component,event,helper){
var checkCmp = component.find("tglbtn").get("v.checked");
component.set("v.exportWithId",checkCmp);
}
})
({
getAccountData : function(component) {
var action=component.get('c.getAccountList');
action.setCallback(this,function(response){
if(response.getState()=='SUCCESS'){
component.set("v.acclist",response.getReturnValue());
}
});
$A.enqueueAction(action);
},
convertListToCSV : function(component, sObjectList){
if (sObjectList == null || sObjectList.length == 0) {
return null;
}
var columnEnd = ',';
var lineEnd = '\n';
// Get the CSV header from the list.
var keys = new Set();
sObjectList.forEach(function(record){
Object.keys(record).forEach(function(key){
if(component.get("v.exportWithId")){
keys.add(key);
}
else{
if(key!="Id")
keys.add(key);
}
});
});
keys = Array.from(keys);
var csvString = '';
csvString += keys.join(columnEnd);
csvString += lineEnd;
for(var i=0; i < sObjectList.length; i++){
var counter = 0;
for(var sTempkey in keys) {
var skey = keys[sTempkey];
// add , after every value except the first.
if(counter > 0){
csvString += columnEnd;
}
// If the column is undefined, leave it as blank in the CSV file.
var value = sObjectList[i][skey] === undefined ? '' : sObjectList[i][skey];
csvString += '"'+ value +'"';
counter++;
}
csvString += lineEnd;
}
return csvString;
},
showToast:function(title,type,message){
var toastEvent = $A.get("e.force:showToast");
if(toastEvent){
toastEvent.setParams({"title": title,"type": type,"message": message}).fire();
}
else{
alert(message);
}
},
})
Output:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.
0 Comments
Post a Comment