Search

Export To Excel Using LWC

Start exporting your Salesforce data to excel like never before. Learn the newest way to achieve this functionality hassle free and say good bye to lengthy code.


sampleExportToExcel.html

<template>

<lightining-button name="Export" label="Export To Excel" onclick={downloadExcel}/>

</template>


sampleExportToExcel.js

import { LightningElement, @api } from "lwc";

import getAccountData from "@salesforce/apex/SampleAccountClass.getAccountData";

export default class Calender extends LightningElement {

accountData = [];

connectedCallBack(){

getAccountData().then((result) =>{

if(result != null && result != '' && result != 'undefined'){

this.accountData = downloadExcel();

}

});

}

downloadExcel(event){

// Prepare a html table

let doc = '<table>';

// Add styles for the table

doc += '<style>';

doc += 'table, th, td {';

doc += ' border: 1px solid black;';

doc += ' border-collapse: collapse;';

doc += '}';

doc += '</style>';

// Add all the Table Headers

doc += '<tr>';

columnHeader = ['Id', 'Name', 'Email'];

this.columnHeader.forEach(element => {

doc += '<th>'+ element +'</th>'

});

doc += '</tr>';

// Add the data rows

this.accountData.forEach(record => {

doc += '<tr>';

doc += '<th>'+record.Id+'</th>';

doc += '<th>'+record.Name+'</th>';

doc += '<th>'+record.Email+'</th>';

doc += '</tr>';

});

doc += '</table>';

var element = 'data:application/vnd.ms-excel,' + encodeURIComponent(doc);

let downloadElement = document.createElement('a');

downloadElement.href = element;

downloadElement.target = '_self';

// use .csv as extension on below line if you want to export data as csv

downloadElement.download = 'Account Template.xls';

document.body.appendChild(downloadElement);

downloadElement.click();

}

}


SampleAccountClass.aspx

public class SampleAccountClass{

@AuraEnabled(cacheable=true)

public static Account getAccountData(){

return [SELECT Id, Name, Email FROM ACCOUNT];

}

}


32 views0 comments

Recent Posts

See All