Introduction :
- Uploading CSV files to create object records in Lightning Web Components (LWC) can be a useful feature for Salesforce users who need to import data from external sources. The process involves parsing the CSV file, mapping the data to the object’s fields, and inserting the records into the database. To accomplish this, you can use the
lightning-file-upload
component to handle the file upload and then process the CSV data to create object records. There are several resources available online that provide step-by-step instructions on how to implement this feature in LWC. By following these resources, Salesforce users can learn how to efficiently import data from a CSV file into their Salesforce org using LWC.
Step 1: Create records using a CSV file that contains records of the Account object.
Step 2: Create the lightning web component and apex class
HTML:
<template>
<lightning-card title=”Process CSV File”>
<div class=”file-uploader”>
<lightning-input label=”” name=”file uploader” onchange={handleFilesChange} type=”file” multiple></lightning-input>
<div class=”error-message”>{fileName}</div>
<lightning-button class=”upload-button” label={UploadFile} onclick={handleSave} variant=”brand” disabled={isTrue}></lightning-button>
</div>
</lightning-card>
<lightning-card title=”Accounts” icon-name=”standard:account”>
<div class=”datatable-container” if:true={data}>
<lightning-datatable data={data} columns={columns} key-field=”id”></lightning-datatable>
</div>
</lightning-card>
</template>
JavaScript:
import { LightningElement, api, track } 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 = this.filesUploaded[0].name;
}
}
handleSave() {
if (this.filesUploaded.length > 0) {
this.uploadFile();
} else {
this.fileName = ‘Please select a CSV file to upload!!’;
}
}
uploadFile() {
if (this.filesUploaded[0].size > this.MAX_FILE_SIZE) {
console.log(‘File Size is too large’);
return;
}
this.showLoadingSpinner = true;
this.fileReader = new FileReader();
this.fileReader.onloadend = () => {
this.fileContents = this.fileReader.result;
this.saveFile();
};
this.fileReader.readAsText(this.filesUploaded[0]);
}
saveFile() {
try {
saveFile({ base64Data: JSON.stringify(this.fileContents), cdbId: this.recordid })
.then(result => {
if (result === null || result.length === 0) {
this.dispatchEvent(
new ShowToastEvent({
title: ‘Warning’,
message: ‘The CSV file does not contain any data’,
variant: ‘warning’,
}),
);
}
else {
this.data = result;
this.fileName = this.fileName + ‘ – Uploaded Successfully’;
this.isTrue = false;
this.showLoadingSpinner = false;
this.dispatchEvent(
new ShowToastEvent({
title: ‘Success!!’,
message: this.filesUploaded[0].name + ‘ – Uploaded Successfully!!!’,
variant: ‘success’,
}),
);
}
})
.catch(error => {
console.error(error);
this.showLoadingSpinner = false;
this.dispatchEvent(
new ShowToastEvent({
title: ‘Error while uploading File’,
message: error.message,
variant: ‘error’,
}),
);
});
} catch (error) {
console.error(error);
this.showLoadingSpinner = false;
this.dispatchEvent(
new ShowToastEvent({
title: ‘Error’,
message: ‘An unexpected error occurred.’,
variant: ‘error’,
}),
);
}
}
}
CSS File :
.file-uploader {
margin-left: 4%;
margin: 0px auto;
width: 300px;
}
.error-message {
margin-top: 8px;
font-size: 12px;
color: red;
}
.upload-button {
margin-top: 16px;
}
.datatable-container {
width: auto;
}
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;
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);
}
if (lstCCToInsert != null)
{
insert lstCCToInsert;
}
return lstCCToInsert;
}
}
Test Class:
@isTest
public class lwcCSVUploaderControllerTest{
Static String base64Data = ‘\”Name,Site,Account Source\\r\\nTest1,Test1.com,web\\r\\nTest2,Test2.com,web\\r\\nTest3,Test3.com,web\\r\\nTest4,Test4.com,web\\r\\n\”‘;
static testmethod void testfileupload(){
Test.startTest();
lwcCSVUploaderController.saveFile(base64Data);
Test.stopTest();
}
}
Step 3: Upload the CSV file in the upload files.
Step 4: Click the Upload CSV File Button.
OUTPUT:
Conclusion :
In conclusion, integrating the lightning-file-upload
component with CSV data processing allows for seamless file uploads and object record creation in LWC. This enables users to easily import data from external sources, contributing to a more streamlined and efficient data management experience within the Salesforce platform.
Related Links :
https://www.merfantz.com/blog/aura-components-vs-lightning-web-components/
https://www.merfantz.com/blog/how-to-call-lightning-web-component-from-visualforce-page/