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.

Afte