In Visualforce we can use ContentType to export data in different formats. But what if we want to do same in Lightning? There is no inbuilt native support provided for this. So today we will check how we can export data in CSV using JavaScript in Lightning.
For this we will create a component in which we will pass the list and then using JavaScript we will make a csv file of that. Using JavaScript we can easily create comma separate CSV file and then can set the data type data:text/csv;charset=utf-8
in JS.

csvExport.cmp
<aura:component>
<aura:attribute name="records" type="sObject[]"/>
<aura:attribute name="fileName" type="String"/>
<lightning:buttonIcon iconName="utility:download" onclick="{!c.downloadCsv}" alternativeText="Export Data" />
</aura:component>
csvExportController.js
({
downloadCsv : function(component, event, helper){
var recordsList = component.get("v.records");
// call the helper function which returns the CSV data as a String
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 = component.get("v.fileName");
document.body.appendChild(hiddenElement); //Required for FireFox browser
hiddenElement.click(); // using click() js function to download csv file
},
})
csvExportHelper.js
({
convertListToCSV : function(component, sObjectList){
if (sObjectList == null || sObjectList.length == 0) {
return null; //
}
// CSV file parameters.
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) {
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;
},
})
csvExportDemoApp.app
<aura:application controller="AccOppListController" extends="force:slds">
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:attribute name="accList" type="List[]" description="Account records" />
<lightning:card iconName="utility:search" title="Export Data in CSV">
<c:csvExportDemo records="{!v.accList}" fileName="new file.csv"/>
<table class="slds-table slds-table_bordered slds-table_cell-buffer">
<thead>
<tr class="slds-text-title_caps">
<th scope="col">
<div class="slds-truncate" title="Account Id">Account Id</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Account Name">Account Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Phone">Phone</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.accList}" var="acc">
<tr>
<th scope="row" data-label="Account Id">
<div class="slds-truncate" title="{!acc.Id}">{!acc.Id}</div>
</th>
<td data-label="Account Name">
<div class="slds-truncate" title="{!acc.Name}">{!acc.Name}</div>
</td>
<td data-label="Phone">
<div class="slds-truncate" title="{!acc.Phone}">{!acc.Phone}</div>
</td>
</tr>
</aura:iteration>
</tbody>
</table>
</lightning:card>
</aura:application>
So code is very simple. We first get the header key and store them into a string. We have also created two separater to separate the column and row. Then we iterate each row and add the comma to separate them. We have handle the blank columns and replace them with empty string. We have first created the comma separated csv using JavaScript and then, JavaScript onclick method we have downloaded the file. So in Lightning we can export data in CSV using JavaScript. The same approach can also be used in VF page
This component can be used with any sobject. It also supports multiple browsers. In my coming post I will also convert this component into Lightning Web Component. If you have still not started studying LWC you can do that here.
Did you like the post or have any question, let me know in comments. Happy Programming 🙂
Wht about related fields?
hai the above code is working fine.but i need to add styles on the excel file like borders for the table and colors for column headers. pls help me
Thanks in advance
You can easily do this in excel as we are just pasting the content in existing excel. Options are available for this in excel.
i need to add styles on the excel file like borders for the table and colors for column headers. pls help me
Thanks in advance
I have a quick question, is there a way this could be modified to export to multiple sheets . If I wanted to export multiple objects into one file.
I don’t think thats possible without any third party JS library(If available).
@Tushar Sharma i have a inline vf page with button to download as csv, it is working for vf page but causing issue in lightning.I find your code above works well for lightning experience can the same be supported in classic as well without any modifications.Thanks in advance.
Yes it will.
Hi Tushar,
I have the same requirement, but i want to sort the data based on recordtype and display in different tables in the same excel. how could we achieve this.?
hi how to exclude special characters like ~@#*^ from the records and export
You need to remove this character in JavaScript unless you vcan remove it from orginal record.
Hi Tushar, I need to covnert into PDF from JS function. Could you please suggest on this,
You can try it with PDF.js or can use VF to generate PDF.
i need to Download CSv File from Lightning Components ,but some data have ‘00123223’ with leading Zeros i need to Download with full number
This is something which you need to handle in excel. You can refer this: https://help.salesforce.com/articleView?id=000336106&type=1&mode=1
Export CSV is not working in salesfore mobile app. Please let me know how can i do this.
Hi Tushar,
I have the same requirement , but the data should be sorted based on RecordType and display them differently in the same excel.
could you please help me in achieving this.
Hi @Tushar
I am not able to download the full data in the CSV file only a few rows 40 rows are downloaded. I am returning the CSV file as a string from Apex. When I send that CSV file as an attachment in the email then after download I can see full data. But when I download that by clicking a button then I am not getting full data. Can you please help?