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

Wednesday, September 4, 2019

How to get month name using apex in salesforce

Sample Code
DateTime dt = Datetime.now();
System.debug('Month ===> '+dt.format('MM'));
System.debug('Month Name Short ===> '+dt.format('MMM'));
System.debug('Full Month Name ===> '+dt.format('MMMM'));


Output

Wednesday, August 28, 2019

Create Object From Spreadsheet using Lightning Object Creator in Salesforce

Lightning Object Creator is a new tool to create an object from the spreadsheet.

Note: Make sure that Lightning Experience should be enabled in your org.

For Demo, I created a sample spreadsheet with columns.

Step 1:
Go to Setup | Object Manager | Select Custom Object from Spreadsheet
                      OR
you can directly access the tool using below link
https://object-creator.salesforce.com/

Step 2
Upload spreadsheets from Microsoft Excel, Google Sheets, or comma-separated value (CSV) files.
Step 3
Salesforce will automatically detect the fields and populate all its record data from Spreadsheet. You can customize the Salesforce field name and field type or leave them as suggested.
Step 4
Define object Properties and click finish

Result