Salesforce- Export to Excel with Lightning Web Component
By: Shankar Morwal
Tags: Web Development, Lightning Web Component, JavaScript, User Interface, Salesforce

Salesforce- Export to Excel with Lightning Web Component

Salesforce- Export to Excel with Lightning Web Component

Lightening web component (LWC) framework is helping JavaScript developers big time in creating good features and innovative user interfaces on Salesforce.

Recently, we had a requirement to make a feature to export an Excel document from LWC component. There were a few options through which I could even export a plain Excel document, but there was almost nothing, no support at all, for styling like colors, borders, alignment, wrap, border colors, etc.

This got me thinking how could technology fail in such a common arena, so I did some internal research and came out with a solution.

Let’s move further to discuss the solution at length-

Integrating JavaScript Library with LWC

In precise words, I decided to use a JavaScript library write-excel-file , which is available on npm. I integrated this library on Lightening Web Components and found out that it was throwing exception due to locker service.

Let’s build an example based on Excel export-

Thereafter, I decided to customize the library write-excel-file to make it compatible with LWC. You can download this version from here.

First, download the write-excel-file.min.js-

Now, make a folder writeExcel in static resources and put the downloaded file write-excel-file.min.js in it.

writeExcel static resource

Create lightening component excelJSDemo

Create a LWC with name excelJSDemo and add the following code to the excelJSDemo.js file.

import { LightningElement } from 'lwc';

import { loadScript } from "lightning/platformResourceLoader";

import workbook from "@salesforce/resourceUrl/excelDemo";

export default class ExcelJSDemo extends LightningElement {

librariesLoaded = false;

objectsData = [

// Object #1

{

name: 'John Smith',

dateOfBirth: new Date(),

cost: 1800,

paid: true

},

// Object #2

{

name: 'Alice Brown Alice Brown Alice Brown Alice Brown Alice Brown Alice Brown',

dateOfBirth: new Date(),

cost: 2600,

paid: false

}

]

schemaObj = [

// Column #1

{

column: 'Name',

type: String,

wrap: 'true',

color: '#ccaaaa',

value: student => student.name

},

// Column #2

{

column: 'Date of Birth',

type: Date,

format: 'mm/dd/yyyy',

value: student => student.dateOfBirth

},

// Column #3

{

column: 'Cost',

type: Number,

format: '#,##0.00',

value: student => student.cost

},

// Column #4

{

column: 'Paid',

type: Boolean,

value: student => student.paid

}

]

renderedCallback() {

console.log("renderedCallback xlsx");

if (this.librariesLoaded) return;

this.librariesLoaded = true;

loadScript(this, workbook + "/writeExcel/write-excel-file.min.js")

.then(async (data) => {

console.log("success------>>>", data);

})

.catch(error => {

console.log("failure-------->>>>", error);

});

}

// calling the download function from xlsxMain.js

async download() {

let _self = this;

// When passing `objects` and `schema`.

await writeXlsxFile(_self.objectsData, {

schema: _self.schemaObj,

fileName: 'file.xlsx'

})

}

}

Update excelJSDemo.html to add a button to start download -

<template>

<lightning-card title="Exceljs file export demo" icon-name="custom:custom14">

<button onclick={download} class="btn success">Download</button>

</lightning-card>

</template>

Update excelJSDemo.js-meta.xml -

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="xlsxDemo">

<apiVersion>46.0</apiVersion>

<isExposed>true</isExposed>

<targets>

<target>lightning__AppPage</target>

<target>lightning__RecordPage</target>

<target>lightning__HomePage</target>

</targets>

</LightningComponentBundle>

Deploy and run your code

Now, you can deploy your code and drag this component to any layout you like. Once you add it to the layout, you will see a download button. I for one, added it as a tab to opportunity layout.

Download button

Once you click the download button, you will be able to download a beautiful Excel sheet with styles and formatting.

This library has many options for styling, check this link to learn more. Mainly, it supports the following styles-

align: string - Horizontal alignment of cell content.

Available values: "left" , "center" , "right" .

alignVertical: string - Vertical alignment of cell content.

Available values: "top" , "center" , "bottom" .

height: number - Row height, in "points".

- Row height, in "points". span: number - Column span.

Even if a cell spans several columns, you still have to provide a value for every cell in every row and column.

rowSpan: number - Row span.

Even if a cell spans several rows, you still have to provide a value for every cell in every row and column.

wrap: boolean - Set to true to "wrap" text when it overflows the cell.

- Set to to "wrap" text when it overflows the cell. fontWeight: string - Can be used to print text in bold.

Available values: "bold" .

color: string - Cell text color (in Hexadecimal format).

Example: "#aabbcc" .

backgroundColor: string - Cell background color (in Hexadecimal format).

Example: "#aabbcc" .

borderColor: string - Cell border color.

Example: "#aabbcc" .

borderStyle: string - Cell border style.

Example: "thick" .

leftBorderColor

leftBorderStyle

rightBorderColor

rightBorderStyle

topBorderColor

topBorderStyle

bottomBorderColor

bottomBorderStyle

That was all, folks! Hope this article was useful for you. Share your queries in the comment box and hit claps 👏 if you liked the blog.