You need to sign in to do that
Don't have an account?
kishore goud 3
exporting data in the format of csv in lighting component
Requirement: There is a button "Export Today " which is used to export account records in the form of csv in lightning component(Account_Detail_Component).In the helper ,we have "convertArrayOfObjectsToCSV" function which is used to convert object records into csv. I am able to display account fields values i.e 'Name','AccountNumber','Id' in csv.But I am not able to display parent account field values.
For example below query return account field values and parent field value
Select id,name,accountnumber,parent.accountnumber from Account where parent.id!=null and parent.accountnumber!=null.Could any one please post javascript code which needs to be used in helper fucntion for displaying parent account records.
Component:
<aura:component controller="CsvDownloadCtrller" implements="force:appHostable">
<aura:attribute name="AcctLst" type="Account[]"></aura:attribute>
<aura:handler name="init" value="{!this}" action="{!c.loadAcctRcrds}"/>
<div class="slds-box slds-box">
<article class="slds-card">
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__body">
<h2 class="slds-card__header-title">
<a href="javascript:void(0);" class="slds-card__header-link slds-truncate" title="Accounts">
<span class="slds-text-heading_small">Account List View</span>
</a>
</h2>
</div>
<div class="slds-no-flex">
<button class="slds-button slds-button_brand" onclick="{!c.exprtTodysRecrds}">Export Today</button>
<button class="slds-button slds-button_brand">Export Weekly</button>
</div>
</header>
</div>
</article>
<article class="slds-card">
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__body">
<h2 class="slds-card__header-title">
<a href="javascript:void(0);" class="slds-card__header-link slds-truncate" title="Accounts">
<span class="slds-text-heading_small">Search Accounts</span>
</a>
</h2>
</div>
</header>
</div>
</article>
<div class="slds-form slds-form_compound">
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
<lightning:select name="select1" label="Account Type" required="true">
<option value="">choose one...</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
</lightning:select>
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input aura:id="field" label="Parent Account Number" name="ParentAccountNumber" />
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input aura:id="field" label="Account Number" name="AccountNumber" />
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
<lightning:textarea name="input1" label="Description" />
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:select name="select1" label="Country" required="true">
<option value="">choose one...</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</lightning:select>
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input type="date" name="input1" label="From Date" />
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input type="date" name="input1" label="To Date" />
</div>
</div>
</div>
</fieldset>
</div>
<div class="slds-no-flex slds-align_absolute-center slds-m-top_xx-large">
<button class="slds-button slds-button_brand" style="width:100px">Search</button>
<button class="slds-button slds-button_brand" style="width:100px">Clear</button>
</div>
</div>
</aura:component>
controller:
({
loadAcctRcrds:function(component,event,helper){
var action = component.get("c.getAccounts");
action.setCallback(this,function(response){
var state = response.getState();
if(state == "SUCCESS"){
component.set("v.AcctLst",response.getReturnValue());
}
else{
alert('failed');
}
});
$A.enqueueAction(action);
},
exprtTodysRecrds : function(component, event, helper) {
var stockData = component.get("v.AcctLst")
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
}
})
Helper:
({
convertArrayOfObjectsToCSV : function(component,objectRecords){
// declare variables
var csvStringResult, counter, keys, columnDivider, lineDivider,parentKey;
// 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 = ['Name','AccountNumber','Id','Parent' ];
//parentKey=['AccountNumber'];
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] ;
/* if(skey=='Parent'){
for(var pTempkey in parentKey){
csvStringResult += '"'+ objectRecords[i][skey][pTempkey]+'"';
}
}*/
// add , [comma] after every String value,. [except first]
if(counter > 0){
csvStringResult += columnDivider;
}
csvStringResult += '"'+ objectRecords[i][skey]+'"';
/* if(csvStringResult.includes("Parent")){
for(var sTemp in parentKey){
var orgnKey = parentKey[sTemp];
csvStringResult += '"'+ objectRecords[i][skey][orgnKey]+'"';
}
} */
counter++;
} // inner for loop close
csvStringResult += lineDivider;
}// outer main for loop close
// return the CSV formate String
return csvStringResult;
},
})
Apex Controller:
public class CsvDownloadCtrller {
@AuraEnabled
public static List<Account> getAccounts(){
return [Select id,name,accountnumber,parent.accountnumber from Account where parent.id!=null and parent.accountnumber!=null];
}
}
For example below query return account field values and parent field value
Select id,name,accountnumber,parent.accountnumber from Account where parent.id!=null and parent.accountnumber!=null.Could any one please post javascript code which needs to be used in helper fucntion for displaying parent account records.
Component:
<aura:component controller="CsvDownloadCtrller" implements="force:appHostable">
<aura:attribute name="AcctLst" type="Account[]"></aura:attribute>
<aura:handler name="init" value="{!this}" action="{!c.loadAcctRcrds}"/>
<div class="slds-box slds-box">
<article class="slds-card">
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__body">
<h2 class="slds-card__header-title">
<a href="javascript:void(0);" class="slds-card__header-link slds-truncate" title="Accounts">
<span class="slds-text-heading_small">Account List View</span>
</a>
</h2>
</div>
<div class="slds-no-flex">
<button class="slds-button slds-button_brand" onclick="{!c.exprtTodysRecrds}">Export Today</button>
<button class="slds-button slds-button_brand">Export Weekly</button>
</div>
</header>
</div>
</article>
<article class="slds-card">
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__body">
<h2 class="slds-card__header-title">
<a href="javascript:void(0);" class="slds-card__header-link slds-truncate" title="Accounts">
<span class="slds-text-heading_small">Search Accounts</span>
</a>
</h2>
</div>
</header>
</div>
</article>
<div class="slds-form slds-form_compound">
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
<lightning:select name="select1" label="Account Type" required="true">
<option value="">choose one...</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
</lightning:select>
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input aura:id="field" label="Parent Account Number" name="ParentAccountNumber" />
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input aura:id="field" label="Account Number" name="AccountNumber" />
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
<lightning:textarea name="input1" label="Description" />
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:select name="select1" label="Country" required="true">
<option value="">choose one...</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</lightning:select>
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input type="date" name="input1" label="From Date" />
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input type="date" name="input1" label="To Date" />
</div>
</div>
</div>
</fieldset>
</div>
<div class="slds-no-flex slds-align_absolute-center slds-m-top_xx-large">
<button class="slds-button slds-button_brand" style="width:100px">Search</button>
<button class="slds-button slds-button_brand" style="width:100px">Clear</button>
</div>
</div>
</aura:component>
controller:
({
loadAcctRcrds:function(component,event,helper){
var action = component.get("c.getAccounts");
action.setCallback(this,function(response){
var state = response.getState();
if(state == "SUCCESS"){
component.set("v.AcctLst",response.getReturnValue());
}
else{
alert('failed');
}
});
$A.enqueueAction(action);
},
exprtTodysRecrds : function(component, event, helper) {
var stockData = component.get("v.AcctLst")
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
}
})
Helper:
({
convertArrayOfObjectsToCSV : function(component,objectRecords){
// declare variables
var csvStringResult, counter, keys, columnDivider, lineDivider,parentKey;
// 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 = ['Name','AccountNumber','Id','Parent' ];
//parentKey=['AccountNumber'];
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] ;
/* if(skey=='Parent'){
for(var pTempkey in parentKey){
csvStringResult += '"'+ objectRecords[i][skey][pTempkey]+'"';
}
}*/
// add , [comma] after every String value,. [except first]
if(counter > 0){
csvStringResult += columnDivider;
}
csvStringResult += '"'+ objectRecords[i][skey]+'"';
/* if(csvStringResult.includes("Parent")){
for(var sTemp in parentKey){
var orgnKey = parentKey[sTemp];
csvStringResult += '"'+ objectRecords[i][skey][orgnKey]+'"';
}
} */
counter++;
} // inner for loop close
csvStringResult += lineDivider;
}// outer main for loop close
// return the CSV formate String
return csvStringResult;
},
})
Apex Controller:
public class CsvDownloadCtrller {
@AuraEnabled
public static List<Account> getAccounts(){
return [Select id,name,accountnumber,parent.accountnumber from Account where parent.id!=null and parent.accountnumber!=null];
}
}
Below code can fullfill your requirements. Hope this will work for you.
Download Data as CSV File With JavaScript In Salesforce Lightning Component :
Sample Code :
apex Controller [csvDownloadCtrl.apxc] :
public class csvDownloadCtrl {
@AuraEnabled
public static list <contact> fetchContact(){
List <contact> returnConList = new List < contact > ();
for(contact con: [SELECT firstName, LastName, Department, MobilePhone From contact LIMIT 1000]) {
returnConList.add(con);
}
return returnConList;
}
}
Above apex class is just return the List of Contact Records.
Lightning Component [csvSample.cmp] :
<aura:component controller="csvDownloadCtrl">
<!--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 display Contact Records-->
<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>
See Code Comments
JavaScript Controller [csvSampleController.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
},
})
See Code Comments
JavaScript Helper [csvSampleHelper.js] :
({
onLoad: function(component, event) {
//call apex class method
var action = component.get('c.fetchContact');
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;
},
})
See Code Comments
If You want add another column to CSV file from object, add Field API name to Line number 33 on JS helper controller. such as -:
keys = ['FirstName','LastName','Department','MobilePhone','Id','CustomFieldApiName__c' ];
TestApp.app :
<aura:application extends="force:slds">
<c:csvSample />
<!-- here c: is org. namespace prefix-->
</aura:application>
Please mark as best answer if it helps you.
Thank You
Ajay Dubedi
If you observe my apex coontroller code
[Select id,name,accountnumber,parent.accountnumber from Account where parent.id!=null and parent.accountnumber!=null]
I am trying to query account field values(id,name,accountnumber) and parent account field values(parent.accountnumber)
I am able to display account field values in CSV.But,I am not able display to parent account field values in CSV.Could you please post code to display parent account field.
Thanks in advance
Ch.Kishore
As I also face the same problem but when I used the below code, it solves my problem.
keys = ['Name',AccountNumber,Parent];
if(skey == 'Parent'){
objectRecords[i][skey] = objectRecords[i].Parent.AccountNumber;
console.log(objectRecords[i][skey]);
}
csvStringResult += '"'+ objectRecords[i][skey]+'"';
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks.
Deepali Kulshrestha
Thanks in advance
Thanks a lot for the solution. It worked perfectly for me.
Regards,
Syed
On my blog i have displayed some data to user, User will select the data that user wants to download from the displayed data. Once user select all those record which user wants to export user has to click on download data button and excel in the csv format will get download.
Also i have shown how to show data from related object in csv as well.
Please refer the below link.
https://www.sfdc-lightning.com/2019/10/export-to-csv-in-lightning-component.html
http://salesforcecodes.com/import-export-data-from-csv-file-using-lightning-component/ (http://salesforcecodes.com/import-export-data-from-csv-file-using-lightning-component/" target="_blank)
here am going to show you, how to import the data and export the data from csv file using lightning component
How to change the colummn header name , because when i use my custom fields in keys ,in my donwloaded csv file the columun name is same as my api name like (Account_Number__c), Instead of this in my csv it should get display as the columm name as AccountNumber
Help me out thanks !
Hi Guru Dev 6,
you can change column names in the CSV file by using wrapper class and return wrapper in js.
I have used this and it solved my problem.
I hope you find the above solution helpful. If it does, please mark it as Best Answer to help others too.
Thanks.
Hassan Mansoor