• WHO WE ARE
  • WHAT WE DO
    • Implementations
      • Salesforce
        • Sales Cloud
        • Service Cloud
        • CPQ
        • Field Service for SMEs
        • Field Service Lightning
      • Salesforce Partner Apps
        • Panda Doc
        • Conga
      • Hubspot
    • Developments
      • Salesforce Customization
      • Custom Application Development
      • AppExchange Product Development
    • Migrations
      • Classic to Lightning Migration
      • Other Systems to Salesforce Migration
    • Integrations
  • HOW WE DO
    • Delivery Model
    • Our Works
  • REACH US
    • Contact Us
    • Careers
  • BLOG
    • WHO WE ARE
    • WHAT WE DO
      • Implementations
        • Salesforce
          • Sales Cloud
          • Service Cloud
          • CPQ
          • Field Service for SMEs
          • Field Service Lightning
        • Salesforce Partner Apps
          • Panda Doc
          • Conga
        • Hubspot
      • Developments
        • Salesforce Customization
        • Custom Application Development
        • AppExchange Product Development
      • Migrations
        • Classic to Lightning Migration
        • Other Systems to Salesforce Migration
      • Integrations
    • HOW WE DO
      • Delivery Model
      • Our Works
    • REACH US
      • Contact Us
      • Careers
    • BLOG
  • [email protected]
  • (+91) 44-49521562
Merfantz - Salesforce Solutions for SMEs
Merfantz - Salesforce Solutions for SMEs
  • WHO WE ARE
  • WHAT WE DO
    • Implementations
      • Salesforce
        • Sales Cloud
        • Service Cloud
        • CPQ
        • Field Service for SMEs
        • Field Service Lightning
      • Salesforce Partner Apps
        • Panda Doc
        • Conga
      • Hubspot
    • Developments
      • Salesforce Customization
      • Custom Application Development
      • AppExchange Product Development
    • Migrations
      • Classic to Lightning Migration
      • Other Systems to Salesforce Migration
    • Integrations
  • HOW WE DO
    • Delivery Model
    • Our Works
  • REACH US
    • Contact Us
    • Careers
  • BLOG

How To Upload CSV File and Create Object Records – LWC

  • October 6, 2023
  • Tech Blogger
  • Field Service Management, Merfantz Developments
  • 0

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.

      CSV FILE
 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.

Upload File

Step 4: Click the Upload CSV File Button.

 

OUTPUT:

Output

Tags: Javascript
  • Previous How To Mass Delete Using List View Button
  • Next How to Send a Custom Notification using Flow
Merfantz Technologies is a leading Salesforce consulting firm dedicated to helping small and medium enterprises transform their operations and achieve their goals through the use of the Salesforce platform. Contact us today to learn more about our services and how we can help your business thrive.

Discover More

Contact Info

  • No 96, 2nd Floor, Greeta Tech Park, VSI Industrial Estate, Perungudi, Chennai 600 096, Tamil Nadu, INDIA
  • (+91) 44-49521562
  • [email protected]
  • 9:30 IST - 18:30 IST

Latest Posts

How to Change Dynamic Salesforce Domain URL December 1, 2023
How to Create Daylight Saving Time (DST) using the formula. November 24, 2023
IMAGE COMPRESSION USING LIGHTNING WEB COMPONENT November 3, 2023

Copyright @2023 Merfantz Technologies, All rights reserved