CsvController.cls
public with sharing class CsvController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts(){
return [SELECT Id, Name, Phone, AnnualRevenue, Industry from Account];
}
}
csvDemo.html
<template>
<lightning-card title="CSV Demo">
<div class="slds-p-around_medium">
<template if:true={accountData}>
<template for:each={accountData} for:item="account">
<p key={account.Id}>{account.Name}</p>
</template>
</template>
<lightning-button label="Generate CSV" onclick={csvGenerator}
variant="brand"></lightning-button>
</div>
</lightning-card>
</template>
csvDemo.js
import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/CsvController.getAccounts'
import {exportCSVFile} from 'c/utils'
export default class CsvDemo extends LightningElement {
accountData
accountHeaders={
Id:"Record Id",
Name:"Name",
AnnualRevenue:"Annual Revenue",
Industry:"Industry",
Phone:"Phone"
}
@wire(getAccounts)
accountHandler({data, error}){
if(data){
console.log(data)
this.accountData = data
}
if(error){
console.error(error)
}
}
csvGenerator(){
//headers, totalData, fileTitle
exportCSVFile(this.accountHeaders, this.accountData, "account_records")
}
}
utils.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
}