Monday, September 9, 2019

Salesforce: Export to Excel with Lightning Web Component

Hello Guys,

I hope you are doing well. In this post, we are going to see an implementation of "Export to Excel" in lightning web components.






Exporting the data in Excel is a very common requirement for Developers. We will see how this can be achieved with Lightning web components.

Following HTML code just do a couple of things.

  •  Show a link to "Download Excel"
  •  Show the data to be exported, in the lightning data table.
  •  Click on the Download Excel button would call the js method called exportToCSV.



exportToExcelDemo.html

 <template>  
   <a target="_self" class="slds-button" download="ExportToCSV.csv" href={hrefdata} onclick={exportToCSV}  
     style="margin-left: 80%;">Download Excel</a>  
   <lightning-datatable data={contactList} columns={contactColumns} key-field="id"  
     hide-checkbox-column="true">  
   </lightning-datatable>  
 </template>  
This js file contains the main logic to export the data.


  • Link click will call the exportToCSV method. This function creates a CSV data required for our excel file. 
  • CSV created based on the controller method getContacts() which passes the contact wrapper.

exportToExcelDemo.js

 import {  
   LightningElement,  
   track  
 } from "lwc";  
 import getContacts from "@salesforce/apex/ExportToExcelDemoController.getContacts";  
 const columns = [{  
     label: "Name",  
     fieldName: "contactName",  
     type: "text"  
   },  
   {  
     label: "Email",  
     fieldName: "contactEmail",  
     type: "text"  
   }  
 ];  
 export default class ExportToExcelDemo extends LightningElement {  
   @track hrefdata;  
   @track contactList;  
   @track contactColumns = columns;  
   connectedCallback() {  
     this.getContacts();  
   }  
   getContacts() {  
     getContacts()  
       .then(result => {  
         this.contactList = result;  
       })  
       .catch(error => {  
         this.error = error;  
         console.log(this.error);  
       });  
   }  
   exportToCSV() {  
     let columnHeader = ["Name", "Email"];  // This array holds the Column headers to be displayd
     let jsonKeys = ["contactName", "contactEmail"]; // This array holds the keys in the json data  
     var jsonRecordsData = this.contactList;  
     let csvIterativeData;  
     let csvSeperator  
     let newLineCharacter;  
     csvSeperator = ",";  
     newLineCharacter = "\n";  
     csvIterativeData = "";  
     csvIterativeData += columnHeader.join(csvSeperator);  
     csvIterativeData += newLineCharacter;  
     for (let i = 0; i < jsonRecordsData.length; i++) {  
       let counter = 0;  
       for (let iteratorObj in jsonKeys) {  
         let dataKey = jsonKeys[iteratorObj];  
         if (counter > 0) {  csvIterativeData += csvSeperator;  }  
         if (  jsonRecordsData[i][dataKey] !== null &&  
           jsonRecordsData[i][dataKey] !== undefined  
         ) {  csvIterativeData += '"' + jsonRecordsData[i][dataKey] + '"';  
         } else {  csvIterativeData += '""';  
         }  
         counter++;  
       }  
       csvIterativeData += newLineCharacter;  
     }  
     console.log("csvIterativeData", csvIterativeData);  
     this.hrefdata = "data:text/csv;charset=utf-8," + encodeURI(csvIterativeData);  
   }  
 }  

Finally, this simple controller method that returns you the contact wrapper containing the data.


ExportToExcelDemoController.cls 

public with sharing class ExportToExcelDemoController { 
   public class ContactWrapper{  
     @AuraEnabled  
     public string contactName;  
     @AuraEnabled  
     public string contactEmail;  
     public ContactWrapper(Contact contactObj){  
       this.contactName = contactObj.Name;  
       this.contactEmail = contactObj.Email;  
     }  
   }  
   @AuraEnabled  
   public static List<ContactWrapper> getContacts(){  
     List<ContactWrapper> contactWrapperList = new List<ContactWrapper>();  
     for(Contact cwObj : [select id, Name, Email from Contact limit 5]){  
       contactWrapperList.add(new ContactWrapper(cwObj));  
     }  
     return contactWrapperList;  
   }  
 }  


It's pretty easy, isn't it?

I hope you enjoyed the learning, please write me back the suggestions, comments or any issues. Let's meet in our next post with more learnings and fun. :)

5 comments:

  1. Hi Amol ,

    Nice post.

    I have one requirement can you help me on that

    ReplyDelete
  2. Can we insert conditional styling on on the exported data like cell color, colspan, rowspan, font etc.

    ReplyDelete
  3. Hi,
    this format is in CSV. Is there a way to download in xls format

    ReplyDelete
  4. Hi,
    is there a way if i have a JSON format field returning from the query ?

    ReplyDelete
  5. Using a hinge design, you can to|you probably can} fold and unfold the cubes in multiple of} instructions. Another model for the gardening-challenged, these cute self-watering planters will maintain your vegetation watered and nourished even if you don’t. The planter is available in} five totally different poses, with some sitting flat and others dangling their legs over a ledge, you may get} actually inventive in staging your planter people on your desk, table, or shelf. When you need a specific stopping point for your drill bit, these printable drill depth stops are a straightforward and economical approach to maintain your drill from going too deeply into your materials. With the pandemic still in full swing, private safety tools is as necessary Cycle Clothing as ever.

    ReplyDelete

Salesforce: Export to Excel with Lightning Web Component

Hello Guys, I hope you are doing well. In this post, we are going to see an implementation of " Export to Excel" in lightn...