Friday, September 13, 2019

Read CSV File using Lightnig Web Component and Apex in salesforce

This post explains how to read CSV file using apex and Lightning Web Component.

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

10 comments:

  1. Exactly similar this i need to do as part of my current project work.

    ReplyDelete
  2. I love this functionality, powerful and easy to implement. Thanks for sharing.

    ReplyDelete
  3. but this is not working in community showing error only upload png,jpg

    ReplyDelete
  4. This is really helpful, thanks a Lot!!!

    ReplyDelete
  5. Thank you so much.

    ReplyDelete
  6. This is terrific thanks for sharing

    ReplyDelete
  7. I am getting error of conversion for my object and i tried to set sytem.debug in apex calss but i coudent get any message.

    ReplyDelete
  8. Hi , thanks for sharing , i have a question , if i want to verify if the name of column is correct and show a message that inform which column name is incorrect that what we need in the csv file .

    How can i do it please ?

    ReplyDelete
  9. i need to add integer data type to this component, how can i do this.

    ReplyDelete