How To Export Data in CSV File From LWC Lightning Data Table?

In Salesforce, we create a custom LWC data table using the lightning-datatable attribute. Since this data table displays a large volume of records, there may be a requirement to share the number of records or all records with users, or to retain the data for analysis.

For this, we can define a functionality in the Lightning web components that extracts and saves data in CSV format. This Salesforce tutorial will teach us how to export data in a CSV file from the LWC Lightning data table.

Export Data in CSV File From LWC Lightning Data Table

In the example below, we will first create an LWC component using the Lightning Datatable component. Within that, we will add a button that triggers the custom clickHandler event, which converts the array of data table records into CSV format.

Now, follow the steps below to create an LWC table with the ability to export data into a CSV file.

1. First, create a controller class that will fetch the records from the object. In this example, we will display the account records in a data table; therefore, enter the code below in the controller class.

public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Industry, AnnualRevenue FROM Account LIMIT 10];
    }
}

2. After this, enter the code below in the HTML file to render the UI of data tables with table columns and the button through which we will download the records.

<template>
    <lightning-card title="Export Data in LWC" icon-name="standard:account">
        <div class="slds-m-around_medium">
            <lightning-datatable
                key-field="Id"
                data={tableData}
                columns={columns}>
            </lightning-datatable>
            <div class="slds-m-top_medium">
                <lightning-button
                    variant="brand"
                    label="Export to CSV"
                    onclick={clickHandler}
                ></lightning-button>
            </div>
        </div>
    </lightning-card>
</template>

Here, we have mapped the columns attribute to render the fields from the columns array in the JavaScript file.

To add the download button, we have used the built-in lightning-button attribute, and it will call the event clickHandler on click to handle the download logic.

3. Enter the code below in the JS file to define the data table columns from the controller class’s fetched records.

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

export default class ExportDataTable extends LightningElement {
    @track tableData = [];
    @track columns = [
        { label: 'Account Name', fieldName: 'Name', type: 'text' },
        { label: 'Industry', fieldName: 'Industry', type: 'text' },
        { label: 'Annual Revenue', fieldName: 'AnnualRevenue', type: 'currency' }
    ];

    @wire(getAccountList)
    wiredAccounts({ error, data }) {
        if (data) {
            this.tableData = data;
        } else if (error) {
            console.error('Error fetching accounts:', error);
        }
    }

    get checkRecord() {
        return this.tableData.length > 0 ? false : true;
    }

    clickHandler() {
        try {
            const selectedRows = this.template
                .querySelector('lightning-datatable')
                .getSelectedRows();
            
            const downloadRecords = selectedRows.length > 0 ? 
                [...selectedRows] : 
                [...this.tableData];

            if (downloadRecords.length > 0) {
                const csvFile = this.convertArrayToCSV(downloadRecords);
                this.createLinkForDownload(csvFile);
            }
        } catch (error) {
            console.error('Error in clickHandler:', error);
        }
    }

    convertArrayToCSV(downloadRecords) {
        const csvHeader = Object.keys(downloadRecords[0]).join(',');
        const csvBody = downloadRecords.map(currItem =>
            Object.values(currItem).join(',')
        );
        return csvHeader + "\n" + csvBody.join("\n");
    }

    createLinkForDownload(csvFile) {
        const downLink = document.createElement("a");
        downLink.href = "data:text/csv;charset=utf-8," + encodeURIComponent(csvFile);
        downLink.target = "_blank";
        downLink.download = "AccountData.csv";
        downLink.click();
    }
}

In this, we have defined the event clickHandler(), this event will check that records are selected on the data table using the method getSelectedRows() and store in the variable selectedRows.

If no rows are selected, it will store all records in the downloadRecords variable. Now, the data stored in the variable is in the form of an array, and to convert it into CSV, we will create a method convertArrayToCSV.

After that, it creates a downloadable file named “AccountData.csv” with createLinkForDownload(). The process is wrapped in a try-catch block to catch and log any errors that may occur.

4. Enter the code below in the meta.xml file to make the component available to the Lightning pages.

<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

5. Deploy the LWC component to the Lightning page, and the Lightning data table will display the account records along with the download button.

Here, select the rows using the checkbox to download specific records, and then click the “Export to CSV (download)” button.

Download the Lightning Data table in CSV file

To download all records displayed on the data table, click on the download button.

Download LWC data table records in CSV format

This way, we can export or download the data from the LWC Lightning data table in a CSV file.

Create a Reusable Utility to Export Data in a CSV File From a Lightning Data Table

If you already have a Lightning data table and need the functionality to export the table data in CSV format. Then, for that use case, we can create a utility component that handles the logic of exporting data in CSV format.

This utility component can be imported into the LWC component where you have defined the data table, and we can then export the data from that LWC table to a CSV file.

1. To create an export csv utility, create an LWC component utility and define data export logic in the utility.js file with the code below.

export function exportCSVFile(headers, totalData, fileTitle){
    if(!totalData || !totalData.length){
        return null
    }
    const jsonObject = JSON.stringify(totalData)
    const result = convertToCSV(jsonObject, headers)
    if(result === null) return
    const blob = new Blob([result])
    const exportedFilename = fileTitle ? fileTitle+'.csv' :'export.csv'
    if(navigator.msSaveBlob){
        navigator.msSaveBlob(blob, exportedFilename)
    } else if (navigator.userAgent.match(/iPhone|iPad|iPod/i)){
        const link = window.document.createElement('a')
        link.href='data:text/csv;charset=utf-8,' + encodeURI(result);
        link.target="_blank"
        link.download=exportedFilename
        link.click()
    } else {
        const link = document.createElement("a")
        if(link.download !== undefined){
            const url = URL.createObjectURL(blob)
            link.setAttribute("href", url)
            link.setAttribute("download", exportedFilename)
            link.style.visibility='hidden'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
        }
    }
    
}
function convertToCSV(objArray, headers){
    const columnDelimiter = ','
    const lineDelimiter = '\r\n'
    const actualHeaderKey = Object.keys(headers)
    const headerToShow = Object.values(headers) 
    let str = ''
    str+=headerToShow.join(columnDelimiter) 
    str+=lineDelimiter
    const data = typeof objArray !=='object' ? JSON.parse(objArray):objArray

    data.forEach(obj=>{
        let line = ''
        actualHeaderKey.forEach(key=>{
            if(line !=''){
                line+=columnDelimiter
            }
            let strItem = obj[key]+''
            line+=strItem? strItem.replace(/,/g, ''):strItem
        })
        str+=line+lineDelimiter
    })
    console.log("str", str)
    return str
}

2. After this, we have to import this utility into the child LWC component. Enter the code below in the JS file to add the export functionality.

import { LightningElement, wire } from 'lwc';
import { exportCSVFile } from 'c/utils';

//rest of the code logic to map the data from controller class//

downloadOpportunityData() {
        console.log('Data before export:', JSON.stringify(this.data));
        const columns = this.columns.reduce((acc, column) => {
            acc[column.fieldName] = column.label;
            return acc;
        }, {});
        console.log('Columns:', JSON.stringify(columns));
        exportCSVFile(columns, this.data, "Opportunity detail");
    }

The columns and data represent the mapping of attributes of an object that are retrieved from the controller class.

In the event downloadOpportunityData will stringify the array of data table columns. After this, we have called the utility method exportCSVFile to export the data into the CSV file.

3. After this, update the HTML file to create the button to trigger the event to download the data in a CSV file.

<lightning-button 
                variant="brand" 
                label="Download in CSV" 
                onclick={downloadOpportunityData}>
            </lightning-button>

4. Deploy the changes to the org, and navigate to the page where the Data table is deployed.

If the button is not visible after refreshing, click Settings > Edit Page, save the changes again in the app builder, and then return to the app page.

Download Lightning data table rcords in CSV file

5. Now, the download button will be visible in the data table, and as we click on it, the table data will be downloaded in a CSV file.

Create a Csv File Downloader Utility in LWC data table

The CSV file will be saved by a label that we have entered while mapping the exportCSVFile in the LWC component.

Salesforce Lightning Data Table Records export in CSV

This way, we can add a download button feature to a LWC Lightning Data Table using a utility component and export the table data as a CSV file.

You may also like to read:


Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.