Hello, folks! Today, we’re diving into an exciting topic: implementing the ‘Export to Excel’ feature in Lightning Web Components.
We often encounter the need to export data in Excel format, and in this post, we’ll explore how to achieve this seamlessly using Lightning web components.
Imagine this scenario:
You have a lightning data table showcasing some valuable data.
Now, wouldn’t it be fantastic if you could provide your users with a simple way to download that data in xls/csv format? Well, you can! With just a few lines of code, we’ll make it happen.
Now, let’s dive into the actual implementation! Below, you’ll find the code that brings the ‘Export to Excel’ functionality to life. So, buckle up and get ready to empower your users with this amazing feature!
Exporting to XLS/CSV Format:
APEX CODE:
The ContactController class retrieves the contact details from the Contact object.
ContactController.cls
public with sharing class ContactController {
@AuraEnabled (cacheable=true)
public static List<Contact> getContacts(){
return [SELECT Id, Name, Email, Phone, LeadSource, AccountId
FROM Contact LIMIT 20];
}
}
LWC CODE:
generateExcel.HTML:
<template>
<!----- LWC table and Download buttons ------->
<lightningcard title="Generate CSV/XLS from Salesforce"
icon-name="standard:contact">
<template if:true={data}>
<lightning-button icon-
name="utility:download" label="Download CSV" onclick={handleDownload
CSV} variant="brand" slot="actions"></lightning-button>
<lightning-button icon-
name="utility:download" label="Download XLS" onclick={handleDownloaX
LS} 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>
</template>
-
- The above code showcases a datatable which displays data from the data property
and uses the columns property to define the columns. - It also includes two buttons for downloading CSV and XLS files respectively.
- When clicked, the buttons trigger the respective download functions.
- The above code showcases a datatable which displays data from the data property
generateExcel.JS:
import { LightningElement, track, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getConta
cts';
export default class GenerateExcel extends LightningElement {
@track error;
@track data;
@track columns = [
{ label: 'Name', fieldName: 'Name' },
{ label: 'Email', fieldName: 'Email' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' },
{ label: 'Lead Source', fieldName: 'LeadSource' },
{ label: 'Account ID', fieldName: 'AccountId' }
];
@wire(getContacts, {})
wireResult({ error, data }) {
if (data) {
this.data = data;
} else if (error) {
this.error = error;
console.log(error);
}
}
handleDownloadCSV() {
this.downloadFile('csv');
}
handleDownloadXLS() {
this.downloadFile('xls');
}
downloadFile(format) {
if (this.data && this.data.length > 0) {
let content = '';
// Adding column headers
this.columns.forEach((col) => {
content += col.label + ',';
});
content += '\n';
// Adding data rows
this.data.forEach((record) => {
this.columns.forEach((col) => {
const value = record[col.fieldName] || '';
content += '"' + value.replace(/"/g, '""') + '",
';
});
content += '\n';
});
const link = document.createElement('a');
//Determine the MIME type of the file based on the requested format
('xls' or 'csv').
const mimeType = format === 'xls' ? 'application/vnd.ms-
excel' : 'text/csv';
//Construct a data URL using the content string and the MIME type.
const dataUrl = 'data:' + mimeType + ';charset=utf-
8,' + encodeURIComponent(content);
link.href = dataUrl;
//Set the download attribute of the <a> element to specify the
filename of the downloaded file, appending the format extension.
link.setAttribute('download', 'ContactDetails.' + format
);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
-
-
- The @wire decorator connects the component to the getContacts Apex method, fetching the contact data.
- The downloadFile() method generates a file by iterating over the data and columns, creating a content string.
- It then creates a download link with the appropriate MIME type and data URL.
- Finally, it triggers a click event on the link to initiate the file download for the user.
-
Voila! The CSV/XLS file is now ready to be downloaded by the user, containing all the contact data.
Downloaded CSV File
So, there you have it! Generating and downloading a CSV/XLS file in Lightning Web Components is pretty straightforward, thanks to the power of LWC and JavaScript. I hope you found this blog post both informative and enjoyable.
Stay tuned for more exciting blog posts where we’ll continue to explore new learnings and have fun
along the way. Happy coding!
Reference:
https://techdicer.com/generate-csv-in-lwc-salesforce/
Also Read : How to Integrate Salesforce with WordPress
Also, if you are in need of a Salesforce certified consultant, look no further. Our team of experienced consultants are experts in all aspects of Salesforce, from implementation to customization and training. We understand the unique needs of your business and can provide tailored solutions that will drive your sales and streamline your processes. With our expertise, you can trust that you are in capable hands.
Thank you for the information!! is it possible to only download selected records?
Your blog always works for me !! Thanks and Keep writing