Download Data as CSV File With JavaScript In Salesforce Lightning Component

Hi guys, Today In this post we are seeing that how to Download/Export Data as CSV File format With Client Side JavaScript controller In Salesforce Lightning Component.

What is the CSV File ?  

CSV stands for “comma-separated values”. CSV is a simple file format used to store tabular data, like a spreadsheet or database. Its data fields are most often separated,  by a comma. Files in the CSV format can be imported to and exported from programs that store data in tables, such as Microsoft Excel or OpenOffice etc.

Prerequisites : basic understanding of Lightning Component, JavaScript and Apex Programming.

In This Sample, we will create a simple Lightning Component which is showing the Contact [salesforce standard object] Records. and also creating a HTML Button to download table data as CSV format.

Output:

CSV File download from lightning component

CSV File:

CSV File download from lightning component

apex Controller [csvDownloadCtrl.apxc]

  • Above apex class is just return the List of Contact Records.
Lightning Component [csvSample.cmp]

  • See Code Comments
JavaScript Controller [csvSampleController.js]

  • See Code Comments
JavaScript Helper [csvSampleHelper.js]

  • 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 -:

TestApp.app

After the winter 17 release you can  use the Lightning Design System style in Lightning Apps by extends=”fore:slds”.  The Salesforce Lightning Design System provides a look & feel that’s consistent with Lightning Experience. Use Lightning Design System styles to give your custom applications a UI that is consistent with Salesforce.

Some Useful Resources : 

Use of Aura:iteration

Use aura:valueInit [aura:handler name=”init”]..

https://www.lightningdesignsystem.com/components/data-tables/

Like our facebook page for new post updates. & Don’t forget to bookmark this site for your future reference. 🙂

if you have any suggestions or issue with it, you can post in comment box  🙂

(Visited 26,051 times, 1 visits today)

89 thoughts on “Download Data as CSV File With JavaScript In Salesforce Lightning Component”

  1. Hi,

    Thanks for the blog.

    Can you please help me how to export data in multiple sheets inside one excel. I have three data tab to export inside one excel sheet.

    Also when I am trying to export the lookup column like CreatedBy.LastName, its not giging any result.

     

     

    Reply
    • Hi abhilash,
      if you have got “undefined” it means you don’t have any data(null) value in record field.
      if you don’t want get “undefined” in csv then add a undefined check in helper javaScript controller i.e

      if(objectRecords[i][skey] != undefined){
      csvStringResult += '"'+ objectRecords[i][skey]+'"';
      }else{
      csvStringResult += '"'+ '' +'"';
      }

      now if you have null value in record field it will be blank in csv instead Of undefined

      thanks

      Reply
  2. Hi Piyush,

    I am not able to post comment in forum neither able to register.
    I need help regarding export to excel. I refer your blog, but its working to export data in 1 sheet for workbook. I need to export data in two/three sheets of a single workbook. Like 1 sheet will contains open cases, 2nd sheet will contain closed cases etc. Request you to please help, if possible.

    Reply
  3. Hi..

    i am getting error when i click on “Download as Csv” button though data is populated.

    Here is the error..

    This page has an error. You might just need to refresh it. Action failed: Ashi:csvSample$controller$downloadCsv [Access is denied. ] Failing descriptor: {Ashi:csvSample$controller$downloadCsv}

    Can u please help me on this?

    Regards,
    Sudheer.

    Reply
    • yes, you can do it by change on Line Number 36 in javaScript Helper
      Use below line :
      csvStringResult += [‘User First Name’,’User Last Name’,’My Department’,’Custom Phone’,’Object Id’ ];
      insteadOf : csvStringResult += keys.join(columnDivider);

      Thanks

      Reply
  4. This is working fine normally. However, in my scenario, I am using an inline vf page on account detail page. In this inline VF page, there is lightning component which has “download as CSV” button. When I click on this button it says “We’d like to open the Salesforce page null… in a new tab. Because of your browser settings, we need your permission first.” in lightning experience. However, it works fine in classic. Any help would be much appreciated.

    Thanks

    Reply
  5. Hi,

    Is there any way we can make Download file Name dynamic.

    this part hiddenElement.download = ‘ExportData.csv’;

    with some present date stamp etc

    Thanks

    Reply
  6. Hi,

    Thank you for the post. It is working fine for me. But I’m looking to fetch related fields as well. For example, I added custom field abc__r.xyz.__c in apex controller. But the value in csv is showing as undefined for all related fields.

    Now in the helper,  for the keys, im using the same api name such as abc__r.xyz.__c.

    keys = [‘abc__r.xyz.__c‘,‘FirstName’,‘LastName’,‘Department’,‘MobilePhone’,‘Id’ ]

    Do I need to follow different approach to retrieve related fields.

    Thank you.

     

     

    Reply
  7. Hi,

    Thank you for the post. It is working fine for me. But I also want to fetch related fields in the soql. For example I need custom field abc__r.xyz__c. Added it in soql.

    Now in the helper, I added api name in the same format abc__r.xyz__c.
    I added it in keys variable as below.
    keys = [‘abc__r.xyz__c‘,’FirstName’,’LastName’,’Department’,’MobilePhone’,’Id’ ];

    But the values in the csv are showing as ‘undefined’. Do I need to follow a different approach to get related fields.

    Thank you.

    Reply
  8. Hi, I’m able to download the CSV file but there’s a special character appearing when it was downloaded. Can u please help me with this

    Reply
  9. Hi,

    Thanks for the blog. It helped me a lot. I have strucked in the mid i have writen a SOQL query with the relationship for eg:- abc__r.xyz__c, i cannot able to get the values while exporting into csv. I have used in the Key[‘abc__r.xyz__c’] but its not working. Please anyone can suggest a solution for this?

    Reply
    • first query abc__r.xyz__c in your apex class SOQL query.

      and in your lightning component add new row in aura:iteration tag :

      {!con.abc__r.xyz__c}

      and in your javaScript helper function on line number 33 add your related field,such as:
      keys = ['FirstName','LastName','Department','Level__c','MobilePhone','Id','abc__r' ];
      Update line number 50 with below statement :
      if(typeof objectRecords[i][skey] === 'object'){
      csvStringResult += '"'+ objectRecords[i][skey].xyz__c+'"';
      }else{
      csvStringResult += '"'+ objectRecords[i][skey]+'"';
      }

      This will be solve your issue
      Thanks

      Reply
  10. Hi Piyush,

    I need to download only selected records with the check box  next to each records by clicking on Download Button. pls help with me download code or logic if possible.

    Reply
  11. Thanks for the code. Is that possible to download the csv if we have paginated the records? What do we need to do in that case? Please clarify. Thanks

    Reply
  12. Hi. This is really useful. I have Custom Label as Excel Columns and it doesnt display translated labels correctly in in the CSV file.

    Reply
  13. Hi ,

    Great blog.  can you please also help me on how to upload the excel using lighting and parse it to perform DML operations on excel records. Through VF I know but in lighting ,facing the issue to pass the file from lighting to apex.

     

    Thanks in advance 🙂

     

    Reply
  14. HI Piyush.. loved the code thanks so much !!

    do we have a similar code for downloading data as XLS file. M not able to find it anywhere

    Reply
  15. HI Piyush .. loved the code thank so much!

    Do we have a similar code for downloading data as xls file as well? m not able to find it anywhere

    Reply
  16. Hi ,

    Thanks for sharing this. It was very helpful.

    Can you please also tell me that how can I get the size of the CSV file and show the indicator of the downloading file that how much size is downloaded.

    Reply
  17. Hi,

    I have a visualforce tab. I am using lightning component to download csv file. this lightning component has been used in visualforce page. VF tab the download button is working fine in salesforce classic and  tried the same thing in lightning I am getting an error “Page doesn’t exist”. Please help me if you have faced the same issue.

     

    Thanks in advance

    Reply
  18. Hi Piyush,

    This is nice post regarding csv download and helpful also but i have a query that if i want to get the lookup field how t pass it on keys. As i am unable to get the parentfield value on export.

    example Account.Name

    Reply
  19. Hi,

    I am using lightning component to download csv file and successfully worked, but I want  header row should in bold.How can I achieve that.If this possible or not ?

    Reply
  20. When i click on the button on chrome, the page will freeze until the process is finished, is this a browser setting issue or can we do something to prevent this? (firefox works fine)

    Reply
  21. Hello ,

    Thanks. This helped me .Actually I need to export large data around 20K records and it is giving me ‘network  error’ when I click on download button for csv download.please advise what can we do in this scenario

    Reply
  22. hello,

    Thanks. It works fine. I have columns highlighted  with some colours based on some conditions and date format these are not coming in the csv. how to get them?.

    Reply
  23. Hey,

     

    This is giving me access is denied in edge browser. I checked all the lines and found that it’s triggering on hiddenelement.click().

     

    Can you please help me out there

    Reply
  24. HI,

    We are unable to get special characters data, data has stopped in csv where special character exists. Please help me with getting special characters data also.

    Thank You,
    Mani

    Reply
  25. Hi,

    The download works fine.But the field value in other language EG: contact Name is ??????it

    it is corrupted in the downloaded csv file .Can we avoid this programatically

    Reply
  26. Their is problem with code it doesn’t work well with permission set assignment or refrenced fields it always shows undefined in our case.

     

     

    Reply
  27. Hello Sfdc monkey,

    Nice explanation for download functionality what about if we have multiple related fields like abc_c.xyz_r.mnp_r.

    How we can fetch this value please help.

     

    Thanks

    PB

    Reply
  28. the above code is working fine. But i want borders also in the excel file is it possible to apply border for a table.

    Thanks in advance

    Reply
  29. The above code is working fine in crome and firefox but in edge and IE, it doesn’t allowed the CSV to download.

    Is there any way to fix this.

    Reply
  30. I am facing a problem. I am binding value like ‘0001234’. Its a string, but in xls sheet, its removing the preceding zeros, populating only ‘1234’. Is there any solution for that?

    Reply
  31. Hi, It is really appreciable work, will help great for users.

    I have multiple tabs in my org, each org had one lightning data table. Is there possibility to down load each tab table as Sheet in single Excel file.

    Reply
  32. Hi ,

    it is working in lightning experience. The same component when i reference in visualforce the download buton is not working in classic experience. If this can work in lightning experience also please let me know.

    Reply
  33. Hi, Thank you for helpful blog like this.

    I implemented the download CSV functionality for my project Requirement.

    But, i have a problem while writing the data into CSV file.

    Problem:  if data contains special character like ‘#’ CSV is stop writing. no error in console.log but, downloaded csv file is in complete. for now, we are replacing the # with space in particular custom field by having if condition in Helper.js file.  like Below:

    if(skey == ‘CustomFieldApiName__c’)
    {
    var v1=”;
    if(objectRecords[i][skey] !== undefined){
    if(objectRecords[i][skey].includes(“#”)){
    v1 = objectRecords[i][skey].replace(/#/g,”);
    csvStringResult += ‘”‘+ v1+'”‘;
    }else{
    csvStringResult += ‘”‘+ objectRecords[i][skey]+'”‘;
    }

    }

    but, i have 25 custom fields in my csv file, can we have dynamic way for this?

     

    Thank you,

    Suma.

     

    Reply

Leave a Comment