Export Aura Component tabular data as CSV

Introduction: 

In this blog, I would like to demonstrate on how to export the lightning data table value into an Excel format using Aura component with help of jQuery. 

Requirement: 

On click Event of a quick action button from the object’s detail page, the first step is to retrieve all the necessary records into a lightning data table. The next step is to download the data as CSV using jQuery. 

Use Case: 

For the demonstration, I created a quick action button on the Account Object , and it retrieves the related contacts. Passing accountId in the Quick Action URL will filter the Contacts related to the Account.  

Components Used: 

  • Aura Component 
  • Server-Side Apex class 
  • Static resource 

 Included jQuery as a resource in the Aura Component. 

<ltng:require scripts=”{!$Resource.JQuery}” /> 

Step 1: Retrieve the related contact records under an Account. 

Helper class (JS code) 

Apex Class method 

Step 2: Build JavaScript code to generate the CSV file format. 

Using the style class get the values of the data table and iterate the header and column values to generate a CSV format. 

The document.createElement() method creates the HTML element specified by tag Name. Here, it creates a <p> element and appends it to the document. 

The header is referred by JavaScript object keys, and rows referred by JavaScript object values. It must be separated by a comma to have a CSV. We use Blob for building a CSV file. 

The URL.createObjectURL() static method generates a string containing a URL which represents the object given in the parameter. Here, it is Blob object. 

Href – The location.href property sets the entire URL of the current page. 

The appendChild() method of the Node interface adds up a node to the end of the list of children corresponding to a specific parent node which moves it from its current position to the new position. 

The HTMLElement.click() method generates a mouse click on an element. 

The removeChild() method of a node interface removes a child node from DOM, and it will return the removed node.  

Output: 

1.Open the Account record & click Contacts Quick action button 

2.After clicking contacts quick action button, the related contacts of Account will be displayed in the data table. 

3.After clicking the download button, the related Contacts will be downloaded as a CSV file.  

Output in CSV  

About MST

At MST Solutions our cornerstone is to adapt, engage and create solutions which guarantee the success of our clients. The talent of our team and experiences in varied business verticals gives us an advantage over other competitors.

Recent Articles

Work with us.

Our people aren’t just employees, they are key to the success of our business. We recognize the strengths of each individual and allow them time and resources to further develop those skills, crafting a culture of leaders who are passionate about where they are going within our organization.