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

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 🙂

Advertisements

4 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

Leave a Reply

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