Generate CSV in LWC Salesforce

by Rijwan Mohmmed
0 comment

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


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];



    <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>
						<div class="slds-media__body">
							<div class="slds-page-header__name">
								<div class="slds-page-header__name-title">
										<span>Generate CSV in LWC Salesforce</span>
										<span class="slds-page-header__title slds-truncate" title="Recently Viewed">TechDicer</span>
	</div> <br/>
    <!----- 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">
    <!----- /LWC table and Download CSV button ------->


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}){
   = data;
        } else if(error){
            this.error = 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 (record) {
            Object.keys(record).forEach(function (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 <; 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 =[i][rowKey] === undefined ? '' :[i][rowKey];
                    csvString += '"'+ value +'"';
            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); = '_self';
        // CSV File Name = 'Contact Data.csv';
        // below statement is required if you are using firefox browser
        // click() Javascript function to download CSV file; 



<?xml version="1.0"?>
<LightningComponentBundle xmlns="">

Output :


Reference :

  1. LWC

You may also like

Leave a Comment