Export Data in CSV using JavaScript in Lightning

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.

Export data in CSV using Lightning in Lightning


    <aura:attribute name="records" type="sObject[]"/>
    <aura:attribute name="fileName" type="String"/>

    <lightning:buttonIcon iconName="utility:download" onclick="{!c.downloadCsv}" alternativeText="Export Data" />


    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



    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 = 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 +'"';

            csvString += lineEnd;

        return csvString;


<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">
    <tr class="slds-text-title_caps">
      <th scope="col">
        <div class="slds-truncate" title="Account Id">Account Id</div>
      <th scope="col">
        <div class="slds-truncate" title="Account Name">Account Name</div>
      <th scope="col">
        <div class="slds-truncate" title="Phone">Phone</div>
      <aura:iteration items="{!v.accList}" var="acc">
              <th scope="row" data-label="Account Id">
                <div class="slds-truncate" title="{!acc.Id}">{!acc.Id}</div>
              <td data-label="Account Name">
                <div class="slds-truncate" title="{!acc.Name}">{!acc.Name}</div>
              <td data-label="Phone">
                <div class="slds-truncate" title="{!acc.Phone}">{!acc.Phone}</div>

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 🙂


10 thoughts on “Export Data in CSV using JavaScript in Lightning

  1. 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

  2. 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

  3. 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.

  4. @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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.