No comments yet

Export to CSV/XLS using Lightning Web Component

In many of the requirements, there is one most common requirement is the exporting orgs data in the form of .csv or .xls. (excel formate). Most of the Salesforce developer may have come across such requirement. Previously using VF pages this was very straight forward to fulfill.

Here we will be discussing the yet another way to export the information in tabular form either as .csv or .xls file using the Lightning Web component (LWC). This is very simple technique without using any external Java Script library we can export any kind of data. Following example illustrate the way we can easily export the information as Steps.

Step1: Create the back end Apex controller which will fetch the required data and pass that to the LWC component. Like in below sample code ExportDataController.cls.

 * @description       : Query the 10 Contacts and return the results
public with sharing class ExportDataController {
    public static List<Contact> getAccountDataToExport(){
        List<Contact> lstContacts = [SELECT Id, FirstName, LastName, Email 
FROM Contact LIMIT 10];
        return lstContacts;

Step 2: Create the LWC component as below and import the Apex controller.
Step 3: Prepare the HTML table in the JavaScript as shown in below example check the exportContactData() function.
Step 4: Create the anchor tag a element using document.createElement() function.

Step 5: Append the anchor element and fire a click event using the click() function of the newly created element.

Note: the usage of

var element = 'data:application/,' + encodeURIComponent(doc);

this is the most important here. can be changed for csv. This line itself decides which type of file you can export data to. LWC : ExportDataAsCsvOrXls


import { LightningElement, track, wire } from 'lwc';
import getAccountDataToExport from '@salesforce/apex/ExportDataController.getAccountDataToExport';

export default class ExportDataAsCsvOrXls extends LightningElement {

    @track conatctData = {}

    columnHeader = ['ID', 'FirstName', 'LastName', 'Email' ]

    wiredData({ error, data }) {
        if (data) {
            console.log('Data', data);
            this.conatctData = data;
        } else if (error) {
            console.error('Error:', error);

        // Prepare a html table
        let doc = '<table>';
        // Add styles for the table
        doc += '<style>';
        doc += 'table, th, td {';
        doc += '    border: 1px solid black;';
        doc += '    border-collapse: collapse;';
        doc += '}';          
        doc += '</style>';
        // Add all the Table Headers
        doc += '<tr>';
        this.columnHeader.forEach(element => {            
            doc += '<th>'+ element +'</th>'           
        doc += '</tr>';
        // Add the data rows
        this.conatctData.forEach(record => {
            doc += '<tr>';
            doc += '<th>'+record.Id+'</th>'; 
            doc += '<th>'+record.FirstName+'</th>'; 
            doc += '<th>'+record.LastName+'</th>';
            doc += '<th>'+record.Email+'</th>'; 
            doc += '</tr>';
        doc += '</table>';
        var element = 'data:application/,' + encodeURIComponent(doc);
        let downloadElement = document.createElement('a');
        downloadElement.href = element; = '_self';
        // use .csv as extension on below line if you want to export data as csv = 'Contact Data.xls';

Step 6: Add either link or button in the html filed of the LWC component like shown in the below sample. And hook up the respective defined JavaScript function to it.

    <div class="slds-box slds-theme--default">
        Click on the link Below to Export data as csv/xls.
        <p class="slds-m-top--large">
            <!-- <a onclick={exportContactData}>Export Contact Data</a> -->
            <lightning-button variant="brand" label="Export Contact data" title="Export Contact Data" onclick={exportContactData}></lightning-button>


Export to CSV/XLS using Lightning Web Component


Using LWC it becomes very easy to export the data in tabular for even you can export the large data. Stay connect we will be coming with another blog where we will be exporting the data by applying some formatting like text background, foreground colors etc.

Post a comment