function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MokshadaMokshada 

create one button on account, upload one csv file to account and whenever I click on button It should create Accounts from the data present in csv

Hi,
create one button on account, upload one csv file to account and whenever I click on button It should create Accounts from the data present in csv file using lightning component. can anyone help how can I do that?


Thanks,
Shri RajShri Raj
Steps:
Create a Lightning Component with a file input field and a button.
On the file input change, use JavaScript to parse the CSV file and extract the data into an array of records.
On the button click, use Apex to insert the records into the Account object.
Create a custom tab for the Lightning Component and add the custom button to the Account page layout.
Here's an example of the JavaScript code for parsing the CSV file:

var files = e.target.files;
var file = files[0];

var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csvData = event.target.result;
var data = [];
var lines = csvData.split(/\r\n|\n/);

// extract header row
var headers = lines[0].split(',');

// extract data rows
for (var i=1; i<lines.length; i++) {
var row = lines[i].split(',');
var record = {};
for (var j=0; j<row.length; j++) {
record[headers[j]] = row[j];
}
data.push(record);
}
}

And here's an example of the Apex code for inserting the records:

@AuraEnabled
public static void insertAccounts(List<Account> accounts) {
insert accounts;
}

 
MokshadaMokshada
Hi,
I was trying to do like below but getting error while uploading csv, can anybody help?

apex:
public with sharing class AccountController {
    @AuraEnabled
    public static String createAccountsFromCSV(String csvData) {
        List<List<String>> rows = parseCSV(csvData);
        if (rows.isEmpty()) {
            return 'The file is empty or in an invalid format.';
        }
        List<Account> accounts = new List<Account>();
        for (List<String> row : rows) {
            Account acc = new Account();
            acc.Name = row[0];
            // set other fields based on the CSV data
            accounts.add(acc);
        }
        try {
            insert accounts;
            return 'Accounts created successfully.';
        } catch (Exception e) {
            return 'An error occurred while creating the accounts: ' + e.getMessage();
        }
    }

    private static List<List<String>> parseCSV(String csvData) {
    List<List<String>> rows = new List<List<String>>();
    List<String> rowData = csvData.split('\n');
    for (String row : rowData) {
        rows.add(row.split(','));
    }
    return rows;
}

}

cmp:
<aura:component controller="AccountController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="file" type="Object"/>
    <aura:attribute name="fileContents" type="String"/>
    <aura:attribute name="message" type="String"/>

    <lightning:input type="file" aura:id="file" onchange="{!c.handleFileUpload}"/>
    <lightning:button label="Create Accounts" onclick="{!c.createAccounts}"/>
    <p>{!v.message}</p>
</aura:component>

js:
({
    handleFileUpload: function (component, event, helper) {
        var fileInput = component.find("file").getElement();
        var file = fileInput.files[0];
        if (file) {
            var reader = new FileReader();
            reader.onloadend = function() {
                component.set("v.fileContents", reader.result);
            }
            reader.readAsText(file);
        }
    },
    createAccounts: function (component, event, helper) {
        var fileContents = component.get("v.fileContents");
        if (!fileContents) {
            component.set("v.message", "Please select a file to upload.");
            return;
        }
        var action = component.get("c.createAccountsFromCSV");
        action.setParams({
            csvData: fileContents
        });
        action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var message = response.getReturnValue();
                component.set("v.message", message);
            } else {
                component.set("v.message", "An error occurred while creating the accounts.");
            }
        });
        $A.enqueueAction(action);
    }
})


Thanks