Hello friends. In this post you will find a code example that helps you to download/export salesforce object data in csv file using lightning web component. so, let's get started,
Export data in csv file in lightning web component
To implement this example, I am using account sobject but you can pick any salesforce object as per your need. Also, in this example I have provided a toggle button that helps to export csv with or without record-id of sobject.
Git Repository - Export Data in CSV File in Lightning Web Component
ExportCSVHandler.apxc
public inherited sharing class ExportCSVHandler {
@AuraEnabled(cacheable = true)
public static List<Account> getAccounts(){
return [SELECT Id, Name, Industry, Type, Phone, Rating FROM Account ORDER BY Name LIMIT 10];
}
}
ExportCSV.html <template>
<lightning-card title="Export Data as CSV in Lightning Web Components" icon-name="doctype:csv">
<template if:true={data}>
<div style="width:100%;padding: 15px">
<div class="slds-float_right">
<lightning-button icon-name="utility:download"
label="Download as CSV"
title="Download CSV File"
onclick={downloadCSVFile} variant="brand"></lightning-button>
</div>
<div class="slds-float_left">
<lightning-input data-id="toggle1" type="toggle" label="Export With Id" checked={checkedtoggle} onchange={changeToggle}></lightning-input>
</div>
</div>
<br/>
<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>
ExportCSV.js import { LightningElement, track } from 'lwc';
// importing apex method
import getAccountList from '@salesforce/apex/ExportCSVHandler.getAccounts';
// imported to show toast messages
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
// datatable columns
const cols = [
{label: 'Name',fieldName: 'Name'},
{label: 'Industry',fieldName: 'Industry'},
{label: 'Type',fieldName: 'Type'},
{label: 'Phone',fieldName: 'Phone',type: 'phone'},
{label: 'Rating',fieldName: 'Rating'},
];
export default class ExportCSV extends LightningElement {
@track error;
@track data;
@track columns = cols;
@track checkedtoggle = false;
//Toggle checkbox to export with record-id or without record-id
changeToggle(event){
this.checkedtoggle = !this.checked;
}
// this constructor invoke when component is created.
// once component is created it will fetch the accounts
constructor() {
super();
this.getallaccounts();
}
// fetching accounts from server using apex handler
getallaccounts() {
getAccountList().then(result => {
this.data = result;
this.error = undefined;
})
.catch(error => {
this.data = undefined;
this.error = error;
this.dispatchEvent(
new ShowToastEvent({
title: 'Error while getting accounts',
message: error.message,
variant: 'error'
}),
);
});
}
// this method validates the data and creates the csv file to download
downloadCSVFile() {
var ischecked= this.checkedtoggle;
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) {
if(ischecked==true){
rowData.add(key);
}
else{
if(key!="Id"){
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 = 'AccountData.csv';
// below statement is required if you are using firefox browser
document.body.appendChild(downloadElement);
// click() Javascript function to download CSV file
downloadElement.click();
}
}
ExportCSV.js-meta.xml <?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>56.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Happy Coding...:)
Thank you.
0 Comments
Post a Comment