Simple LWC Data Export to Excel Using SheetJS

Introduction

Lightning Web Components (LWC) is a modern web development framework offered by Salesforce to build responsive and feature-rich applications on the Salesforce Lightning platform. While LWC provides robust data visualization capabilities, there might be situations where users need to export data from an LWC to an Excel sheet for further analysis or sharing purposes. In this blog post, we will explore how to achieve this functionality using the SheetJS library. SheetJS is a powerful JavaScript library that allows us to manipulate and export data to various spreadsheet formats, including Excel (.xlsx) files.

Prerequisites:

Before diving into the implementation, make sure you have the following prerequisites in place:

  1. Salesforce Developer Account: Access to a Salesforce developer account or a Salesforce sandbox environment.
  2. Salesforce CLI: Install Salesforce CLI to work with Salesforce projects and deploy LWC components.
  3. SheetJS Library: Download or link to the SheetJS library in your Salesforce project. You can find it on the official SheetJS GitHub repository.

Step-by-Step Implementation:

Step 1: Set up the Salesforce Project

Create a new Salesforce project or use an existing one using Salesforce CLI. Ensure that you have enabled the Lightning Web Components in your project.

Step 2: Include SheetJS Library

Include the SheetJS library in your project by either downloading the library files from here: https://cdn.sheetjs.com/xlsx-0.20.0/package/dist/xlsx.full.min.js

DO NOT “COPY AND PASTE”! The file should be explicitly downloaded. Copying and pasting corrupts the source code and the component will fail in subtle ways. The easiest approach is to right-click the link and select “Save Link As…”

Setup > Home > Search ‘Static Resource’ > Click on ‘New’ button > Add a static resource

Step 3: Create the Lightning Web Component

Create a new Lightning Web Component to display the data that you want to export to the Excel sheet. For demonstration purposes, let’s assume we have a simple LWC called “ExportToExcel.”

Step 4: Design the User Interface

In the “ExportToExcel” component’s HTML file, create a button that users can click to trigger the export functionality. Add an HTML table or any other element that contains the data to be exported.

<!-- exportToExcel.html -->
<template>
<div>
<lightning-button label="Export to Excel" title="Export Data" onclick={exportToExcel}></lightning-button>
<!-- Add your data in a table or any other desired format here -->
</div>
</template>

Step 5: Implement the Export Functionality

In the “ExportToExcel” component’s JavaScript file, import the necessary SheetJS libraries and write the exportToExcel function. This function will handle the process of exporting data to an Excel sheet.

// exportToExcel.js
import { LightningElement } from 'lwc';
import SheetJS from '@salesforce/resourceUrl/SheetJS'; // The static resource for SheetJS
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
export default class ExportToExcel extends LightningElement {
async connectedCallback() {
await loadScript(this, SheetJS); // load the library
// At this point, the library is accessible with the `XLSX` variable
this.version = XLSX.version;
console.log('version: '+this.version);
}
exportToExcel() {
// Sample table data for demonstration purposes
const tableData = [
['John Doe', 30, 'john.doe@example.com'],
['Jane Smith', 28, 'jane.smith@example.com'],
['Michael Johnson', 35, 'michael.johnson@example.com'],
// Add more data as needed
];
const filename = 'ExportToExcel.xlsx';
const workbook = XLSX.utils.book_new();
const headers = [];
const worksheetData = [];
for (const record of tableData) {
worksheetData.push({
"Name": record[0],
"Age": record[1],
"Email":record[2]
});
}
const worksheet = XLSX.utils.json_to_sheet(worksheetData, { header: headers });
XLSX.utils.book_append_sheet(workbook, worksheet, 'ExportToExcel');
const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
// Create a download link and click it programmatically to initiate the download
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
// Release the object URL to free up memory
URL.revokeObjectURL(a.href);
}
}

Step 6: Test the Export Functionality

Deploy your LWC to your Salesforce environment and navigate to the page where you placed the “ExportToExcel” component. Click the “Export to Excel” button, and the data should be exported to an Excel file named “ExportToExcel.xlsx.”

Conclusion

In this blog post, we explored how to export data from a Lightning Web Component to an Excel sheet using the powerful SheetJS library. By incorporating this functionality into your LWC applications, you can empower users to export data for further analysis, reporting, or sharing with others. The combination of Lightning Web Components and SheetJS offers a seamless and efficient solution for managing and manipulating data within Salesforce environments. Happy coding!

About the blog

SFDCLessons is a blog where you can find various Salesforce tutorials and tips that we have written to help beginners and experienced developers alike. we also share my experience and knowledge on Salesforce best practices, troubleshooting, and optimization. Don’t forget to follow us on:

Newsletter

Subscribe to our email newsletter to be notified when a new post is published.

Advertisements
Advertisements

Arun Kumar

Arun Kumar is a Salesforce Certified Platform Developer I with over 7+ years of experience working on the Salesforce platform. He specializes in developing custom applications, integrations, and reports to help customers streamline their business processes. Arun is passionate about helping businesses leverage the power of Salesforce to achieve their goals.

This Post Has One Comment

Leave a Reply