Hi Folks, In this blog we will try to understand how we can upload CSV file from LWC and How to read CSV file and Insert records using Apex in Salesforce.
CSV File that we are going to read:-
LWC Component-
fileUpload.html
<template>
<lightning-card title="CSV Uploader ">
<div class="slds-box slds-m-around_medium">
<lightning-file-upload accept={acceptedFormats}
label="Attach CSV File"
onuploadfinished={uploadFileHandler}>
</lightning-file-upload>
</div>
</lightning-card>
</template>
fileUpload.js
import { LightningElement,track } from 'lwc';
import loadCSVData from '@salesforce/apex/CSVController.loadCSVData';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class FileUploadExcel extends LightningElement {
get acceptedFormats() {
return ['.csv'];
}
@track contentDocumentId;
@track recordCount;
uploadFileHandler( event ) {
const uploadedFiles = event.detail.files;
// to get File Name
console.log('file name is:-'+uploadedFiles[0].name);
// to get document id
console.log('document id is:-'+uploadedFiles[0].documentId);
this.contentDocumentId=uploadedFiles[0].documentId;
loadCSVData({ contentDocumentId : this.contentDocumentId })
.then((result)=>{
this.recordCount=result;
const event = new ShowToastEvent({
title: 'Success',
message:
this.recordCount+' Account records inserted Successfully.',
variant:'success',
mode:'dismissible'
});
this.dispatchEvent(event);
})
.catch((error)=>{
this.error = error;
const event=new ShowToastEvent({
title:'Error',
variant:'error',
message:'Error while creating Records',
mode:'dismissible'
})
this.dispatchEvent(event);
})
}
}
fileUpload.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<masterLabel>CSV File Uploader </masterLabel>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightningCommunity__Default</target>
<target>lightningCommunity__Page</target>
</targets>
</LightningComponentBundle>
Apex Class
public with sharing class CSVController {
@AuraEnabled
public static string loadCSVData(Id contentDocumentId){
ContentVersion contentVersionObj = [ SELECT Id, VersionData FROM
ContentVersion WHERE
ContentDocumentId =:contentDocumentId ];
list<account> acclist=new list<Account>();
String data= contentVersionObj.VersionData.toString();
string[] csvFileLines=data.split('\n');
for(Integer i=1;i<csvFileLines.size();i++){
string[] csvRecordData = csvFileLines[i].split(',');
Account accObj = new Account() ;
accObj.name = csvRecordData[0] ;
accObj.rating = csvRecordData[1];
accObj.Industry = csvRecordData[2];
acclist.add(accObj);
}
insert acclist;
return string.valueOf(acclist.size());
}
}
Output-
If you have any comments or queries about this, please feel free to mention them in the comments section below.
Hello! I would like to Lear how to do that. I have a situation where I need to upload a file xls and I would like to do that with apex class I am so grateful if you can help me.
ReplyDeleteI am also following the same question. Please let me know if you found something
ReplyDeleteHi.. what if I need to insert datetime field?
ReplyDelete