This post explains how to read CSV file using apex and Lightning Web Component.
Sample CSV File
ReadCSVFileInLWC.html
ReadCSVFileInLWC.js
Apex Class
Output
Sample CSV File
ReadCSVFileInLWC.html
<template>
<lightning-card icon-name="custom:custom19" title='Read CSV File Demo In LWC'>
<div style="margin-left: 3%">
<lightning-file-upload accept={acceptedFormats}
label="Attach receipt"
multiple="multiple"
onuploadfinished={handleUploadFinished}
record-id={recordId}></lightning-file-upload>
</div>
<div if:true={error}>
{error}
</div><br/>
<div if:true={data}>
<lightning-datatable columns={columns}
data={data}
hide-checkbox-column="true"
key-field="id"></lightning-datatable>
</div>
</lightning-card>
</template>
ReadCSVFileInLWC.js
import { LightningElement, track, api } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import readCSV from '@salesforce/apex/LWCExampleController.readCSVFile';
const columns = [
{ label: 'Name', fieldName: 'Name' },
{ label: 'Industry', fieldName: 'Industry' },
{ label: 'Rating', fieldName: 'Rating'},
{ label: 'Type', fieldName: 'Type'},
{ label: 'Website', fieldName: 'Website', type:'url'}
];
export default class ReadCSVFileInLWC extends LightningElement {
@api recordId;
@track error;
@track columns = columns;
@track data;
// accepted parameters
get acceptedFormats() {
return ['.csv'];
}
handleUploadFinished(event) {
// Get the list of uploaded files
const uploadedFiles = event.detail.files;
// calling apex class
readCSV({idContentDocument : uploadedFiles[0].documentId})
.then(result => {
window.console.log('result ===> '+result);
this.data = result;
this.dispatchEvent(
new ShowToastEvent({
title: 'Success!!',
message: 'Accounts are created based CSV file!!!',
variant: 'success',
}),
);
})
.catch(error => {
this.error = error;
this.dispatchEvent(
new ShowToastEvent({
title: 'Error!!',
message: JSON.stringify(error),
variant: 'error',
}),
);
})
}
}
Apex Class
public inherited sharing class LWCExampleController {
@AuraEnabled
public static list<Account> readCSVFile(Id idContentDocument){
list<Account> lstAccsToInsert = new list<Account>();
if(idContentDocument != null) {
// getting File Data based on document id
ContentVersion objVersion = [SELECT Id, VersionData FROM ContentVersion WHERE ContentDocumentId =:idContentDocument];
// split the file data
list<String> lstCSVLines = objVersion.VersionData.toString().split('\n');
for(Integer i = 1; i < lstCSVLines.size(); i++){
Account objAcc = new Account();
list<String> csvRowData = lstCSVLines[i].split(',');
System.debug('csvRowData====> '+csvRowData);
objAcc.Name = csvRowData[0]; // accName
objAcc.Industry = csvRowData[1];
objAcc.Rating = csvRowData[2];
objAcc.Type = csvRowData[3];
objAcc.Website = csvRowData[4];
lstAccsToInsert.add(objAcc);
}
try{
if(!lstAccsToInsert.isEmpty()) {
insert lstAccsToInsert;
}
}
catch (Exception ex) {
throw new AuraHandledException(ex.getMessage());
}
}
return lstAccsToInsert;
}
}
Output