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

How To Export Data in CSV File From LWC Lightning Data Table?
by: Bijay Kumar
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary: In this tutorial, we learn how to create a custom Lightning Web Component (LWC) in Salesforce that includes a data table using the `lightning-datatable` attribute. The component also has a feature that allows users to export data displayed in the table to a CSV file. **Key Steps Involved:** 1. **Setting Up the Controller**: First, create a controller class to fetch records from the Account object. The controller method `getAccountList()` retrieves up to 10 account records. 2. **Building the UI**: In the HTML file, we set up the `lightning-datatable` to display account records and add a button for exporting data. 3. **JavaScript Logic**: We define the columns of the data table and fetch data from the controller. A method `clickHandler()` checks if specific rows are selected for download. If no rows are selected, it downloads all displayed records in CSV format. 4. **CSV Conversion**: The method `convertArrayToCSV()` converts the record array into CSV string format, and `createLinkForDownload()` facilitates downloading the CSV file. 5. **Component Deployment**: Deploy the LWC component to the Lightning page, allowing users to select records and download them. 6. **Reusable Utility**: The tutorial also introduces a reusable utility component to export data from any existing data table to a CSV format, highlighting how to create and use an export function. ### Key Takeaways: - Users can export data from Salesforce LWC data tables into CSV files easily. - The tutorial provides both step-by-step instructions to build a full component and a utility for existing tables. ### Additional Context: CSV (Comma-Separated Values) files are commonly used for data exchange because they can be easily opened in spreadsheet applications like Microsoft Excel or Google Sheets, making it convenient for data analysis or reporting. ### SEO Hashtags: #Salesforce #LWC #LightningWebComponents #CSVExport #DataTables #SalesforceTutorials #WebDevelopment #SoftwareEngineering #SalesforceDevelopment #DataManagement


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

For this, we can define a functionality in the Lightning web components that can extract and save 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 below example, we will first create an LWC component using lightning-datatable that will create the data table, and in that will add a button that will trigger the custom event clickHandler that will convert the array of data table record and convert it into csv format.

Now, follow the steps below to create an LWC table with the functionality of exporting the 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 the data table, so 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 below code 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>

In this, we have mapped the columns attribute to render the fields from the columns array in the JS file.

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

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

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 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 errors if they occur.

4. Enter the below code 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 through the checkbox to download specific records and click the Export to CSV (download) button.

Download the Lightning Data table in CSV file

To download all records displayed on the data table, simply 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 Reusable Utility to Export Data in CSV File From Lightning Data Table

In case, you already have a lightning data table and you just need the functionality that can export the table data in a CSV format. Then for that use case, we can create an utility component that will handle the logic of exporting data in CSV.

This utility component can be imported into the LWC component in which you have defined the data table, and we can then export the data of that LWC table in the 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 in 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 are the mapping of the attributes of an object that are fetched 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 on refresh, click settings> Edit Page, save the changes again in the app builder, and 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 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 download button feature in a LWC lightning data table using an utility component and export the table data in CSV file.

You may also like to read:


The post How To Export Data in CSV File From LWC Lightning Data Table? appeared first on SalesForce FAQs.


March 13, 2025 at 03:21PM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce