Create Object Records:
- Importing and creating records from CSV files can save valuable time and effort.
- Salesforce provides the lightning-file-upload component for this purpose.
- After uploading a CSV file using the lightning-file-upload component, JavaScript and Apex can be used to process the file and extract the data.
Step 1: Create a CSV file that contains records of the Account object.
Step 2: Create the lightning web component and apex class
HTML:
<template>
<template if:true={showLoadingSpinner}>
<div style=”z-index: 10000 !important;”>
<lightning-spinner alternative-text=”Uploading……” size=”medium” style=”z-index: 10000 !important;”></lightning-spinner>
</div>
</template>
<lightning-card title=”Process CSV File”>
<div style=”margin-left:4%; margin:0px auto; width: 300px;”>
<div>
<lightning-input label=”” name=”file uploader” onchange ={handleFilesChange} type=”file” multiple></lightning-input>
</div>
<br/>
<div class=”slds-text-body_small slds-text-color_error”>{fileName}
</div>
<br/>
<div>
<lightning-button class=”slds-m-top–medium” label={UploadFile} onclick ={handleSave} variant=”brand” disabled={isTrue}></lightning-button>
</div>
</div>
<br/><br/>
</lightning-card>
<lightning-card title=”Accounts” icon-name=”standard:account”>
<div style=”width: auto;”>
<template if:true={data}>
<lightning-datatable data={data} columns={columns} key-field=”id”></lightning-datatable>
</template>
</div>
</lightning-card>
</template>
JavaScript:
import { LightningElement, track, api } from ‘lwc’;
import saveFile from ‘@salesforce/apex/lwcCSVUploaderController.saveFile’;
import {ShowToastEvent} from ‘lightning/platformShowToastEvent’;
const columns = [
{ label: ‘Name’, fieldName: ‘Name’ },
{ label: ‘Site’, fieldName: ‘Site’, type: ‘url’ },
{ label: ‘Account Source’, fieldName: ‘AccountSource’ }
];
export default class LwcCSVUploader extends LightningElement {
@api recordid;
@track columns = columns;
@track data;
@track fileName = ”;
@track UploadFile = ‘Upload CSV File’;
@track showLoadingSpinner = false;
@track isTrue = false;
selectedRecords;
filesUploaded = [];
file;
fileContents;
fileReader;
content;
MAX_FILE_SIZE = 1500000;
handleFilesChange(event) {
if(event.target.files.length > 0) {
this.filesUploaded = event.target.files;
this.fileName = event.target.files[0].name;
}
}
handleSave() {
if(this.filesUploaded.length > 0) {
this.uploadHelper();
}
Else
{
this.fileName = ‘Please select a CSV file to upload!!’;
}
}
uploadHelper()
{
this.file = this.filesUploaded[0];
if (this.file.size > this.MAX_FILE_SIZE)
{
window.console.log(‘File Size is to long’);
return ;
}
this.showLoadingSpinner = true;
this.fileReader= new FileReader();
this.fileReader.onloadend = (() =>
{
this.fileContents = this.fileReader.result;
this.saveToFile();
});
this.fileReader.readAsText(this.file);
}
saveToFile() {
saveFile({ base64Data: JSON.stringify(this.fileContents), cdbId: this.recordid})
.then(result => {
window.console.log(‘result ====> ‘);
window.console.log(result);
this.data = result;
this.fileName = this.fileName + ‘ – Uploaded Successfully’;
this.isTrue = false;
this.showLoadingSpinner = false;
this.dispatchEvent(
new ShowToastEvent({
title: ‘Success!!’,
message: this.file.name + ‘ – Uploaded Successfully!!!’,
variant: ‘success’,
}),
);
})
.catch(error => {
window.console.log(error);
this.dispatchEvent(
new ShowToastEvent({
title: ‘Error while uploading File’,
message: error.message,
variant: ‘error’,
}),
);
});
}
}
js-meta.xml:
<?xml version=”1.0″ encoding=”UTF-8″?>
<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata”> <apiVersion>48.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
<target>lightningCommunity__Page</target>
<target>lightningCommunity__Default</target> </targets>
</LightningComponentBundle>
Apex Class:
public class lwcCSVUploaderController
@AuraEnabled
public static List<Account> saveFile(String base64Data)
{
String data = JSON.deserializeUntyped(base64Data).toString();
list<Account> lstCCToInsert = new list<Account>();
list<String> lstCSVLines = data.split(‘\n’);
for(Integer i = 1; i < lstCSVLines.size(); i++){
Account acc = new Account();
String csvLine = lstCSVLines[i];
String prevLine = csvLine;
Integer startIndex;
Integer endIndex;
while(csvLine.indexOf(‘”‘) > -1)
{
if(startIndex == null)
{
startIndex = csvLine.indexOf(‘”‘);
csvLine = csvLine.substring(0, startIndex) + ‘:quotes:’ + csvLine.substring(startIndex+1, csvLine.length());
}
else
{
if(endIndex == null)
{
endIndex = csvLine.indexOf(‘”‘);
csvLine = csvLine.substring(0, endIndex) + ‘:quotes:’ + csvLine.substring(endIndex+1, csvLine.length());
}
}
if(startIndex != null && endIndex != null){
String sub = csvLine.substring(startIndex, endIndex);
sub = sub.replaceAll(‘,’, ‘:comma:’);
csvLine = csvLine.substring(0, startIndex) + sub + csvLine.substring(endIndex, csvLine.length());
startIndex = null;
endIndex = null;
}
}
List<String> csvRowData = new List<String>();
for(String column : csvLine.split(‘,’)){
column = column.replaceAll(‘:quotes:’, ”).replaceAll(‘:comma:’, ‘,’);
csvRowData.add(column);
}
acc.Name = csvRowData[0];
acc.Site = csvRowData[1];
acc.AccountSource = csvRowData[2];
lstCCToInsert.add(acc);
}
insert lstCCToInsert;
return [Select Id, Name, Site, AccountSource From Account Where CreatedDate>=:Date.TODAY()];
}
}
Step 3: Upload the CSV file in the upload files.
Step 4: Click the Upload CSV File Button.
OUTPUT: