Skip to main content

Generating CSV in Lightning Web Components (LWC) - A Step-by-Step Guide

Exporting tabular data into CSV (Comma-Separated Values) files directly from the browser is a high-value feature for enterprise Salesforce applications. Lightning Web Components (LWC) allow developers to format client-side data dynamically and trigger browser-level downloads without server roundtrips.

In plain words: Generating CSV files in LWC builds a formatted string using JavaScript array operations, converts it into a Data URI or Blob, and triggers an anchor tag click to download the spreadsheet directly to the user's machine.

Prerequisites

  • Salesforce Developer Org: An active developer sandbox or scratch org.
  • Salesforce CLI: Installed locally to generate and deploy LWC components.
  • Basic JavaScript ES6 Knowledge: Array methods (map, join, forEach) and DOM handling.

Step-by-Step Implementation

Step 1: Create the LWC Component

Use Salesforce CLI to generate a new component named csvGenerator in your local project repository:

sf project generate component -n csvGenerator -d force-app/main/default/lwc --type lwc

Step 2: Build the HTML Template (csvGenerator.html)

Construct a simple Lightning Card UI containing an action button:

<template>
    <lightning-card title="CSV Generator" icon-name="utility:download">
        <div class="slds-m-around_medium">
            <lightning-button 
                label="Generate CSV" 
                variant="brand" 
                onclick={generateCSV}>
            </lightning-button>
        </div>
    </lightning-card>
</template>

Step 3: Implement JavaScript Export Logic (csvGenerator.js)

Format data rows, escape column strings, construct the CSV payload, and attach an anchor element to trigger the browser download:

import { LightningElement } from 'lwc';

export default class CsvGenerator extends LightningElement {
    generateCSV() {
        const csvRows = [
            ['Name', 'Email', 'Phone'],
            ['John Doe', 'john.doe@example.com', '(123) 456-7890'],
            ['Jane Smith', 'jane.smith@example.com', '(987) 654-3210']
        ];

        // Format rows into CSV strings with double quotes around items
        let csvContent = '';
        csvRows.forEach(row => {
            const csvRow = row.map(item => `"${item}"`).join(',');
            csvContent += csvRow + '\n';
        });

        // Create dynamic anchor element to invoke file download
        const hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
        hiddenElement.target = '_blank';
        hiddenElement.download = 'sample_data.csv';
        hiddenElement.click();
    }
}
Common Developer Mistake: Forgetting to escape column values containing commas or quotes. Always enclose row values in double quotes (`"${item}"`) to prevent data splitting across unexpected columns in Excel.

Step 4: Configure Component Metadata (csvGenerator.js-meta.xml)

Expose the component so administrators can add it to Lightning App Pages and Record Pages:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>60.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Step 5: Deploy to Salesforce

Push your updated source code to your default authorized Salesforce org:

sf project deploy start --source-dir force-app/main/default/lwc/csvGenerator

Step 6: Add and Test on a Lightning Page

  • In Salesforce, navigate to Setup > Lightning App Builder.
  • Edit an existing App Page or Record Page layout.
  • Drag the csvGenerator component onto your canvas, save, and activate the page.
  • Click the Generate CSV button to instantly download sample_data.csv.
When exporting large datasets (>1000 records), construct a JavaScript Blob using new Blob([csvContent], { type: 'text/csv' }) and use URL.createObjectURL(blob) to avoid browser URI string length limits.
Implementation Summary
  • Execution Context: 100% Client-Side JavaScript calculation.
  • Data Structure: Two-dimensional arrays joined via commas and newlines.
  • Download Trigger: Programmatic instantiation and click event on an HTML anchor tag (<a>).

Conclusion

Client-side CSV generation in Lightning Web Components provides a fast, lightweight mechanism for data extraction. Combining JavaScript string manipulation with dynamic DOM anchor downloads empowers users to export records seamlessly across any device.