Download Opportunity Record As CSV.

In this blog we are going to learn about downloading data as CSV here I have used the example of standard object called opportunity. You can use any of object as per your requirement

let’s start with creating a new  LWC component if you haven’t configure your VS Code for LWC you can setup by follow configure VS Code for LWC.

csvutils.js

				
					export function exportCSVFile(headers, totalData, fileTitle){
    if(!totalData || !totalData.length){
        return null
    }
    const jsonObject = JSON.stringify(totalData)
    const result = convertToCSV(jsonObject, headers)
    if(!result){
        return null
    }
    const blob = new Blob([result])
    const exportedFileName = fileTitle? fileTitle+'.csv':'export.csv'
    if(navigator.msSaveBlob){
        navigator.msSaveBlob(blob, exportedFileName)
    } else if (navigator.userAgent.match(/iPhone|iPad|iPod/i)){
        const link = window.document.createElement('a')
        link.href='data:text/csv;charset=utf-8,' + encodeURI(result);
        link.target = "_blank"
        link.download=exportedFileName
        link.click()
    } else {
        const link = window.document.createElement('a')
        if(link.download !== undefined){
            const url = URL.createObjectURL(blob)
            link.setAttribute("href", url)
            link.setAttribute("download", exportedFileName)
            link.style.visibility='hidden'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
        }
    }
}

function convertToCSV(objArray, headers){
    const columnDelimiter = ','
    const lineDelimiter = '\r\n'
    const actualHeaderKey = Object.keys(headers)
    const headerToShow = Object.values(headers)
    
    let str = ''
    str+=headerToShow.join(columnDelimiter)
    str+=lineDelimiter
    const data = typeof objArray !=='object' ? JSON.parse(objArray):objArray
    data.forEach(obj=>{
        let line =''
        actualHeaderKey.forEach(key=>{
            if(line !=''){
                line+=columnDelimiter
            }
            
            let strItem = obj[key] ? obj[key]+'': ''
            line+=strItem? strItem.replace(/,/g, ''):strItem
        })
        str+=line+lineDelimiter
    })
    return str
}
				
			

csvutils.js-meta.xml

				
					<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>
				
			

downloadDataAsCSV.html

Nothing is in HTML.

downloadDataAsCSV.Js

				
					import { LightningElement, wire, api} from 'lwc';
import {exportCSVFile} from 'c/csvutils'
import { CloseActionScreenEvent } from 'lightning/actions';
import getopportunities from '@salesforce/apex/downloaddataAsCSV.getopportunities'

export default class DownloadDataAsCSV extends LightningElement {
    @api recordId
    oppHeaders={
        Id:"Record Id",
        Name:"Name"
    }
    @wire(getopportunities, {oppId : '$recordId'})
    oppData({data, error}){
        if(data){
            console.log(data)
            exportCSVFile(this.oppHeaders, data, "opp_records")
            this.dispatchEvent(new CloseActionScreenEvent());
        }
        if(error){
            console.error(error)
        }
    }
}
				
			

downloadDataAsCSV.js-meta.xml

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

downloadDataAsCSV..cls (Apex class)

				
					public class downloaddataAsCSV {
    @AuraEnabled(cacheable=true)
    public static List<Opportunity> getopportunities(Id oppId){
        return [SELECT Id, Name FROM Opportunity WHERE Id =:oppId];
    }
}
				
			

Create a Action button on opportunity .

You can Export by click on Export button.

Output :-

Leave a Comment