Generate CSV in LWC Salesforce

by Rijwan Mohmmed
2 comments
generate-csv-in-lwc-salesforce

Hello friends, today we will discuss Generate CSV in LWC Salesforce. CSV files are the best things that we can easily show the data by column header. We will fetch the data from the contact object and show it in the LWC Datatable. Also, I will create a button for downloading the CSV file. In this way, we can export the data and download the CSV file. We can open CSV files in Google Sheets or MS office.

Also, check this: Call Apex methods synchronously in LWC

generate-csv-in-lwc-salesforce-output-techdicer
generate-csv-in-lwc-salesforce-output-techdicer

Key Highlights :

  1. CSV file to show the data in an Excel sheet.
  2. Easily download by clicking the button.

Code :

AccountDataController.cls :

public with sharing class AccountDataController {
    @AuraEnabled (cacheable=true)
    public static List<Contact> fetchContacts(){
        return [SELECT Id, Name, Email, Phone, LeadSource, AccountId
                FROM Contact
                LIMIT 2000];
    }
}

generateCSVLWC.HTML:

<template>

    <!------Header------->
    <div class="slds-tabs_card">
		<div class="slds-page-header">
			<div class="slds-page-header__row">
				<div class="slds-page-header__col-title">
					<div class="slds-media">
						<div class="slds-media__figure">
							<span class="slds-icon_container slds-icon-standard-opportunity">
								 <lightning-icon icon-name="standard:recipe" alternative-text="recipe" title="recipe"></lightning-icon>
                            </span>
						</div>
						<div class="slds-media__body">
							<div class="slds-page-header__name">
								<div class="slds-page-header__name-title">
									<h1>
										<span>Generate CSV in LWC Salesforce</span>
										<span class="slds-page-header__title slds-truncate" title="Recently Viewed">TechDicer</span>
									</h1>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div> <br/>
    <!------/Header------->
    <!----- LWC table and Download CSV button ------->
	<lightning-card title="Generate CSV in LWC Salesforce" icon-name="standard:contact">
        
		
        <template if:true={data}>
            <lightning-button icon-name="utility:download" label="Download CSV" title="Download CSV File"
						onclick={downloadCSVFile} variant="brand" slot="actions"></lightning-button>
			<div class="slds-m-around_medium">
				<!-- Datatable component -->
				<lightning-datatable columns={columns} data={data} hide-checkbox-column="true" key-field="id">
				</lightning-datatable>
			</div>
		</template>
	</lightning-card>
    <!----- /LWC table and Download CSV button ------->
</template>

generateCSVLWC.JS:

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

// datatable columns
const cols = [
    {label: 'Name',fieldName: 'Name'}, 
    {label: 'Email',fieldName: 'Email'},
    {label: 'Phone',fieldName: 'Phone',type: 'phone'}, 
    {label: 'LeadSource',fieldName: 'LeadSource'}, 
    {label: 'Account Id',fieldName: 'AccountId'}, 
];

export default class GenerateCSVLWC extends LightningElement {
    @track error;
    @track data;
    @track columns = cols;

    @wire(fetchContacts, {})
    wireResult({error, data}){
        if(data){
            this.data = data;
        } else if(error){
            this.error = error;
            console.log(error);
        }
    }

    // this method validates the data and creates the csv file to download
    downloadCSVFile() {   
        let rowEnd = '\n';
        let csvString = '';
        // this set elminates the duplicates if have any duplicate keys
        let rowData = new Set();

        // getting keys from data
        this.data.forEach(function (record) {
            Object.keys(record).forEach(function (key) {
                rowData.add(key);
            });
        });

        // Array.from() method returns an Array object from any object with a length property or an iterable object.
        rowData = Array.from(rowData);
        
        // splitting using ','
        csvString += rowData.join(',');
        csvString += rowEnd;

        // main for loop to get the data based on key value
        for(let i=0; i < this.data.length; i++){
            let colValue = 0;

            // validating keys in data
            for(let key in rowData) {
                if(rowData.hasOwnProperty(key)) {
                    // Key value 
                    // Ex: Id, Name
                    let rowKey = rowData[key];
                    // add , after every value except the first.
                    if(colValue > 0){
                        csvString += ',';
                    }
                    // If the column is undefined, it as blank in the CSV file.
                    let value = this.data[i][rowKey] === undefined ? '' : this.data[i][rowKey];
                    csvString += '"'+ value +'"';
                    colValue++;
                }
            }
            csvString += rowEnd;
        }

        // Creating anchor element to download
        let downloadElement = document.createElement('a');

        // This  encodeURI encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).
        downloadElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvString);
        downloadElement.target = '_self';
        // CSV File Name
        downloadElement.download = 'Contact Data.csv';
        // below statement is required if you are using firefox browser
        document.body.appendChild(downloadElement);
        // click() Javascript function to download CSV file
        downloadElement.click(); 
    }

}

generateCSVLWC.js-meta.xml:

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>54.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
	</targets>
</LightningComponentBundle>

Output :

generate-csv-lwc-salesforces-output-techdicer

Reference :

  1. LWC
What’s your Reaction?
+1
2
+1
0
+1
0
+1
0
+1
2
+1
0

You may also like

2 comments

Fahad Matin April 13, 2023 - 9:35 am

This was really helpfull

Reply
Rijwan Mohmmed April 14, 2023 - 5:19 pm

Thanks

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.