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
santhanam Arunachalamsanthanam Arunachalam 

How to upload csv file using lightning component?

Hi All,

  I have requirement to upload CSV file into Salesforce using lightning component then this record will insert in Sobject records.Please guide me on this scenario.

Thanks,
Santhanam
Maharajan CMaharajan C
Hi Santhanam,

The below code i have done for Account CSV Insert which is workning code i done this for my learning.

So you can refer this code:

==========================

Apex Class

=============


public class UploadAccountfromLEX {
    
    @AuraEnabled
    public static string insertData(String strfromlex)
    {
        String returnresponse ='';
        List<Account> AccoutnListtoInsert = new List<Account>();
        system.debug('@@@ strfromlex = ' + strfromlex);
        List<fieldWrapper> datalist = (List<fieldWrapper>) JSON.deserialize(strfromlex, List<fieldWrapper>.class);
        system.debug('@@@ datalist = ' + datalist);
        system.debug('@@@ datalistSize = ' + datalist.size());
        for(fieldWrapper wrapper: datalist)
        {
            Account acc =new  Account();
            acc.Name = wrapper.company;
            acc.Description = wrapper.Description;
            acc.Phone = wrapper.phone;
            AccoutnListtoInsert.add(acc);
        }
        if(AccoutnListtoInsert.size() > 0)
        {
            try {
                insert AccoutnListtoInsert;
                returnresponse = 'SUCCESS';
            }
            catch(Exception ex)
            {
                returnresponse = 'ERROR';
            }
        }
        return returnresponse;
    }
  
    public class fieldWrapper {

    public String Company;
        
    public String Description;

    public String phone;

  } 
}




===========================

Aura Component

============


<aura:component controller="UploadAccountfromLEX" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global">

    <div>
        <input type="file" class="file" aura:id="file" />
        <ui:button label="Create Accounts" press="{!c.CreateRecord}"/>
    </div>
        

</aura:component>


=============================

Component JS COntroller

=========


({
    CreateRecord: function (component, event, helper) {
        var fileInput = component.find("file").getElement();
        var file = fileInput.files[0];
        alert(file);
        if (file) {
        console.log("File");
        var reader = new FileReader();
        reader.readAsText(file, "UTF-8");
        reader.onload = function (evt) {
            console.log("EVT FN");
            var csv = evt.target.result;
            console.log('@@@ csv file contains'+ csv);
            var result = helper.CSV2JSON(component,csv);
            console.log('@@@ result = ' + result);
            //console.log('@@@ Result = '+JSON.parse(result));
            helper.CreateAccount(component,result);
            
        }
        reader.onerror = function (evt) {
            console.log("error reading file");
        }
    }

    }
    
    
})


============================

Component JS Helper

===============


({
    CSV2JSON: function (component,csv) {
    console.log('@@@ Incoming csv = ' + csv);
        
        //var array = [];
        var arr = []; 
        
        arr =  csv.split('\n');;
        //console.log('@@@ Array  = '+array);
        console.log('@@@ arr = '+arr);
        arr.pop();
        var jsonObj = [];
        var headers = arr[0].split(',');
        for(var i = 1; i < arr.length; i++) {
            var data = arr[i].split(',');
            var obj = {};
            for(var j = 0; j < data.length; j++) {
                obj[headers[j].trim()] = data[j].trim();
                //console.log('@@@ obj headers = ' + obj[headers[j].trim()]);
            }
            jsonObj.push(obj);
        }
        var json = JSON.stringify(jsonObj);
        console.log('@@@ json = '+ json);
        return json;

        
    },
    
    CreateAccount : function (component,jsonstr){
     console.log('@@@ jsonstr' + jsonstr);
    var action = component.get("c.insertData");
    alert('@@@ Server Action' + action);    
        action.setParams({
                "strfromlex" : jsonstr
            });
        action.setCallback(this, function(response) {
            var state = response.getState();
            alert(state);
            if (state === "SUCCESS") {  
            alert("Accounts Inserted Succesfully");            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                     alert('Unknown');
                }
            }
        }); 
        
        $A.enqueueAction(action);    
        
}
})

Can you please Let me know if it helps or not!!!

If it helps don't forget to mark this as a best answer!!!


Thanks,
Raj
Ajay K DubediAjay K Dubedi
Hi Santhanam, 

Below Sample code can fulfill your requirements. Hope this will work for you.

COMPONENT:
<aura:component controller="ContactListController">
    <ltng:require scripts="/resource/JQ/js/jquery.min.js"/>
    <aura:attribute name="accounts" type="account[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="singleAcc" type="account[]"/>
    <aura:attribute name="newAccount" type="Account" default="{'sobjectType':'Account'}"/>
    <aura:attribute name="accList" type="Account[]" />
            <div class="slds-page-header" role="banner">
          <div class="slds-media">
            <div class="slds-media__figure">
          <h1 class="slds-page-header__title">Accounts</h1>
            </div>
            <div class="slds-media__body">
              <p>Details Of Accounts</p>
            </div>
              <lightning:button variant="brand" label="Download Csv" iconName="utility:download" iconPosition="left" onclick="{!c.downloadCsv}" />
              <lightning:button variant="brand" label="New" iconName="utility:new" iconPosition="left" onclick="{!c.newAccount }" />
          </div>
        </div>
<div id="save_notification" style="display:none; text-align:center;">
<h3>Your Data Successfully Saved.</h3>
</div>
<div id="delete_notification" style="display:none; text-align:center;">
<h3>Your Data Successfully Deleted.</h3>
</div>

<!-- For New Window of Account Start -->
<div id="PreviewpopupForNewAccount" style="display: none;">
<div class="demo-only" style="height: 640px;">
  <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
    <div class="slds-modal__container">
      <header class="slds-modal__header">
        <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" onclick="{!c.CancelNew}" title="Close">
          <!--<svg class="slds-button__icon slds-button__icon_large" aria-hidden="true">
            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/icons/utility-sprite/svg/symbols.svg#close"></use>
          </svg> //-->
          <span class="slds-assistive-text">Close</span>
        </button>
        <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Your Account Details</h2>
        <p class="slds-m-top_x-small">Details Of Your Page Here !</p>
      </header>
      <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
      <form>
        <ui:inputText aura:id="newAccountName" label="Account Name"
                        class="slds-input"
                        labelClass="slds-form-element__label"
                        value="{!v.newAccount.Name}"
                        required="true"/>
    <ui:inputText aura:id="numberOfEmployees" label="Number Of Employees"
                        class="slds-input"
                        labelClass="slds-form-element__label"
                        value="{!v.newAccount.NumberOfEmployees}"
                        required="true"/>
         <ui:inputText aura:id="accountNumber" label="Account Number"
                        class="slds-input"
                        labelClass="slds-form-element__label"
                        value="{!v.newAccount.AccountNumber}"
                        required="true"/>
   <ui:inputText aura:id="phone" label="Phone"
                        class="slds-input"
                        labelClass="slds-form-element__label"
                        value="{!v.newAccount.Phone}"
                        required="true"/>
   <ui:inputText aura:id="annualRevenue" label="Annual Revenue"
                        class="slds-input"
                        labelClass="slds-form-element__label"
                        value="{!v.newAccount.AnnualRevenue}"
                        required="true"/>
  </form>
      </div>
      <footer class="slds-modal__footer">
        <button class="slds-button">
            <lightning:button iconName="utility: save" label="Save" onclick="{!c.newSaveAcc}"/>
            <lightning:button iconName="utility: close" label="Cancel" onclick="{!c.CancelNew}"/>
        </button>
      </footer>
    </div>
  </section>
  <div class="slds-backdrop slds-backdrop_open"></div>
</div>   
</div>
<!-- For New Window of Account Finish -->
<!-- Whole Account Details show here (Start) -->
<table id="details" class="slds-table slds-table_bordered slds-table_cell-buffer">
    <thead>
        <tr class="slds-text-title_caps">
            <th scope="col">
             <div class="slds-truncate"><h1>Account Name</h1></div>
            </th>
            <th scope="col">
             <div class="slds-truncate"><h1>No Of Employees</h1></div>
            </th>
            <th scope="col">
                <div class="slds-truncate"><h1>View / Edit</h1></div>
            </th>
            <th scope="col">
             <div class="slds-truncate"><h1>Delete</h1></div>
            </th>
        </tr>
    </thead>
 <tbody>
        <aura:iteration items="{!v.accounts}" var="account">
        <tr>
            <td data-label="Account Name">
                <div class="slds-truncate" title="Cloudhub">{!account.Name}</div>
            </td>
            <td data-label="Account NumberOfEmployees">
                <div class="slds-truncate" title="Cloudhub">{!account.NumberOfEmployees}</div>
            </td>
            <td data-label="Account Preview And Edit">
            <!-- <a href="" onclick="{!c.AccPreview}">VIEW<input type="text" id="ac" value="{!account.Name}" /></a> -->
            <lightning:button variant="brand" label="View" iconName="utility:preview" iconPosition="left" onclick="{! c.AccPreview }" value="{!account.Id}" />
              <!--   <button class="slds-button" id="acc_id" onclick="{!c.AccPreview}">
                    <a><input type="hidden" id="acc" value="{!account.Id}" /><lightning:icon iconName="action:preview"/></a>
                </button>  -->
            </td>
            <td data-label="Account Delete">
                <lightning:button variant="brand" label="Delete" iconName="utility:delete" iconPosition="left" onclick="{! c.AccDelete }" value="{!account.Id}" />
            </td>
        </tr>
        </aura:iteration>
 </tbody>
</table>
<!-- For Preview Window Start -->
<div id="Previewpopup" style="display: none;">
<div class="demo-only" style="height: 640px;">
  <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
    <div class="slds-modal__container">
      <header class="slds-modal__header">
        <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" onclick="{!c.Cancel}" title="Close">
          <!--<svg class="slds-button__icon slds-button__icon_large" aria-hidden="true">
            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/icons/utility-sprite/svg/symbols.svg#close"></use>
          </svg> //-->
          <span class="slds-assistive-text">Close</span>
        </button>
        <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Your Account Details</h2>
        <p class="slds-m-top_x-small">Details Of Your Page Here !</p>
      </header>
      <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
       <aura:iteration items="{!v.singleAcc}" var="acc">
         <lightning:input aura:id="accountName" name="accountName" label="Account Name" value="{!acc.Name}" />
            <lightning:input aura:id="numberOfEmployees" name="NumberOfEmployees" label="Number Of Employees" value="{!acc.NumberOfEmployees}" />
            <lightning:input aura:id="accountNumber" name="accountNumber" label="Account Number" value="{!acc.AccountNumber}" />
            <lightning:input aura:id="phone" name="phone" label="Phone" value="{!acc.Phone}" />
            <lightning:input aura:id="annualRevenue" name="annualRevenue" label="Annual Revenue" value="{!acc.AnnualRevenue}" />
  </aura:iteration> 
      </div>
      <footer class="slds-modal__footer">
        <button class="slds-button">
            <lightning:button iconName="utility: save" label="Save" onclick="{!c.saveAcc}"/>
            <lightning:button iconName="utility: close" label="Cancel" onclick="{!c.Cancel}"/>
        </button>
      </footer>
    </div>
  </section>
  <div class="slds-backdrop slds-backdrop_open"></div>
</div>   
</div>
<!-- For Preview Window Finish -->
</aura:component>


CONTROLLER:

({
    doInit : function(component, event) {
        var action = component.get("c.findAllAccounts");
        action.setCallback(this, function(a) {
            component.set("v.accounts", a.getReturnValue());
        });
        $A.enqueueAction(action);
    },
// --- New Account Details Save ---//
 newAccount : function(component, event, helper) {
     document.getElementById('PreviewpopupForNewAccount').style.display = 'block'; 
 },
    newSaveAcc : function(component, event, helper) {
        /*var accName= component.get("v.newAccount");
        var accList=[];
        var newobJ={};
        newobJ.sObjectType= 'Account';
        newobJ.Name=accName.Name;
        newobJ.NumberOfEmployees=accName.NumberOfEmployees;
        newobJ.AccountNumber=accName.AccountNumber;
        newobJ.Phone=accName.Phone;
        newobJ.AnnualRevenue=accName.AnnualRevenue;
        accList.push(newobJ);
        component.set("v.accList",accList);
       
        component.set("v.accList",component.get("v.newAccount"));
        console.log('newobJ--->'+newobJ);
        var action = component.get("c.newAccounts");
     action.setParams({
         "accList":JSON.stringify(component.get("v.accList"));
     });
     $A.enqueueAction(action);
        */
/*        var accList=[];
         var newAc = component.get("v.newAccount");
      console.log("New Ac = " + newAc);
          accList.push(newAc);
         console.log("accList = " + JSON.stringify(accList));
        component.set("v.accList",accList);
        console.log('----> '+JSON.stringify(component.get("v.accList")));
*/
       var action = component.get("c.newAccounts");
     action.setParams({
            "accList" : component.get("v.newAccount")
        });
     $A.enqueueAction(action);
        document.getElementById('PreviewpopupForNewAccount').style.display = 'none';
        //--- Successfully Save Data shown here start ---//
        document.getElementById("save_notification").style.display = "block";
        myFunction();
        var myVar;
        function myFunction() {
            myVar = setTimeout(alertFunc, 5000);
        }
        function alertFunc() {
          document.getElementById("save_notification").style.display = "none";
        }
        //--- Successfully Save Data shown here end ---//
 },
    CancelNew : function(component, event, helper) {
        alert('Cancel');
     document.getElementById('PreviewpopupForNewAccount').style.display = 'none';
 },
// --- Preview or View Start --- //
    AccPreview : function(component, event, helper) {
     document.getElementById('Previewpopup').style.display = 'block';
        var evt = event.getSource().get("v.value");
        console.log('evt----> '+evt);   
        var acc_id= component.get("c.getAccountSingleData");
        acc_id.setParams({
            "acid" : evt
        });
        acc_id.setCallback(this,function(result){
        console.log('------->'+JSON.stringify(result.getReturnValue()));
        component.set("v.singleAcc", result.getReturnValue());
        });
        $A.enqueueAction(acc_id);

 },
// --- Save Data Start --- //
    saveAcc : function(component, event, helper) {
    var con = component.get("v.singleAcc");
    var evt = event.getSource();
    console.log('evt----> '+evt);
    var save_action = component.get("c.saveAccount");
   
    save_action.setParams({
     "accList": con
        });
    $A.enqueueAction(save_action);
    document.getElementById('Previewpopup').style.display = 'none';
     var action = component.get("c.findAllAccounts");
        action.setCallback(this, function(a) {
            component.set("v.accounts", a.getReturnValue());
           
        });
        $A.enqueueAction(action);
        document.getElementById("save_notification").style.display = "block";
        //--- Successfully Save Data shown here start ---//
        myFunction();
        var myVar;
        function myFunction() {
            myVar = setTimeout(alertFunc, 5000);
        }
        function alertFunc() {
          document.getElementById("save_notification").style.display = "none";
        }
        //--- Successfully Save Data shown here end ---//
 },
// --- Delete Data Start --- //
    AccDelete : function(component, event, helper){
        var deleteId = event.getSource().get("v.value");
        console.log('delete Event----> '+deleteId);   
        var delAcc = component.get("c.delAccountDetails");
        delAcc.setParams({
            "delAccount" : deleteId
        });
        $A.enqueueAction(delAcc);
        var action = component.get("c.findAllAccounts");
        action.setCallback(this, function(a) {
            component.set("v.accounts", a.getReturnValue());
        });
        $A.enqueueAction(action);
        //--- Successfully Save Data shown here start ---//
        document.getElementById("delete_notification").style.display = "block";
        myFunction();
        var myVar;
        function myFunction() {
            myVar = setTimeout(alertFunc, 5000);
        }
        function alertFunc() {
          document.getElementById("delete_notification").style.display = "none";
        }
        //--- Successfully Save Data shown here end ---//
    },
// --- Cancel View Account Details Start --- //
  Cancel : function(component, event, helper) {
     document.getElementById('Previewpopup').style.display = 'none';
 },
    downloadCsv : function (c, e, h){
        h.downloadCsv_Helper(c, e, h);
    },
})


HELPER:

({
 downloadCsv_Helper : function(c, e, h) {
  var stockData = c.get("v.accounts");
        var csv = h.convertArrayOfObjectsToCSV(c,stockData);  
         if (csv == null){return;}
      var hiddenElement = document.createElement('a');
          hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
          hiddenElement.target = '_self'; //
          hiddenElement.download = 'ExportData.csv';
          document.body.appendChild(hiddenElement);
       hiddenElement.click();
 },
    convertArrayOfObjectsToCSV : function(c,objectRecords){
        var csvStringResult, counter, keys, columnDivider, lineDivider;
        if (objectRecords == null || !objectRecords.length) {
            return null;
         } 
        columnDivider = ',';
        lineDivider =  '\n';
        keys = ['Name','NumberOfEmployees','Id' ];
        csvStringResult = '';
        csvStringResult += keys.join(columnDivider);
        csvStringResult += lineDivider;
        for(var i=0; i < objectRecords.length; i++){  
            counter = 0;
             for(var sTempkey in keys) {
                var skey = keys[sTempkey] ; 
                  if(counter > 0){
                      csvStringResult += columnDivider;
                   }  
               csvStringResult += '"'+ objectRecords[i][skey]+'"';
               counter++;
            }
             csvStringResult += lineDivider;
          }
        return csvStringResult;       
    },
})

APEX CLASS:

public with sharing class ContactListController {
    @AuraEnabled
    public static List<Account> findAllAccounts() {
        return [SELECT Id, Name, NumberOfEmployees FROM Account LIMIT 50];
    }
    @AuraEnabled
    public static void newAccounts(Account accList){
        system.debug('accList------->'+accList);
        insert accList;
    }
    @AuraEnabled
    public static List<Account> getAccountSingleData(string acid) { //string acc_id
        system.debug('Account Name------'+acid);
        return [SELECT id, name, NumberOfEmployees,AccountNumber,Phone,AnnualRevenue FROM Account WHERE ID =: acid];
    }
    @AuraEnabled
    public static void saveAccount(Account acc){
        system.debug('acc----->'+acc);
         insert acc;
    }
    @AuraEnabled
    public static void delAccountDetails(string delAccount) {
        system.debug('Delete Account id ------'+delAccount);
        Account ac = [select id from Account where Id =: delAccount];
        delete ac;
    }
}


Please mark this as best answer if this solves your problem.

Thank you,
Ajay Dubedi
santhanam Arunachalamsanthanam Arunachalam
Hi Maharajan,

   Thanks for your code sharing and  I am able to upload csv file but it will display error msg in console log.PFA.

Error msg upload excelfile

Pls need your help.

Thanks,
Santhanam
rishabh rathor 18rishabh rathor 18
Hi Maharajan, Its is working perfect as my expectation . can we show the csv file and then insert?
help me soon!!
Maharajan CMaharajan C
Hi Rishabh,

You can refer the below code:

Once you have choosen the file it will show the Modal with CSV Data.


Component:

<aura:component controller="UploadAccountfromLEX" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global">
    
    <aura:attribute name="ShowModule" type="boolean" default="false"/>

    <div>
        <input type="file" class="file" aura:id="file" onchange="{!c.showfiledata}"/>
        <ui:button label="Create Accounts" press="{!c.CreateRecord}"/>
    </div>
    
    <aura:if isTrue="{!v.ShowModule}">
        
        <!--###### MODAL BOX Start######--> 
            <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
                <div class="slds-modal__container">
                    <!-- ###### MODAL BOX HEADER Start ######-->
                    <header class="slds-modal__header">
                        <lightning:buttonIcon iconName="utility:close"
                                              onclick="{! c.closeModel }"
                                              alternativeText="close"
                                              variant="bare-inverse"
                                              class="slds-modal__close"/>
                        <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate"> CSV Data </h2>
                    </header>
                    <!--###### MODAL BOX BODY Part Start######-->
                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                        <div id="dvCSV">
                        </div>
                    </div>
                    <!--###### MODAL BOX FOOTER Part Start ######-->
                    <footer class="slds-modal__footer">
                        <lightning:button variant="neutral" 
                                          label="Cancel"
                                          title="Cancel"
                                          onclick="{! c.closeModel }"/>
                    </footer>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
            <!--###### MODAL BOX Part END Here ######-->
        
    </aura:if>
    
    
</aura:component>

============================
JS Controller:

({
    CreateRecord: function (component, event, helper) {
        var fileInput = component.find("file").getElement();
        var file = fileInput.files[0];
        alert(file);
        if (file) {
        console.log("File");
        var reader = new FileReader();
        reader.readAsText(file, "UTF-8");
        reader.onload = function (evt) {
            
            console.log("EVT FN");
            var csv = evt.target.result;
            console.log('@@@ csv file contains'+ csv);
            var result = helper.CSV2JSON(component,csv);
            console.log('@@@ result = ' + result);
            //console.log('@@@ Result = '+JSON.parse(result));
            helper.CreateAccount(component,result);
            
        }
        reader.onerror = function (evt) {
            console.log("error reading file");
        }
    }

    },
    
    closeModel: function(component, event, helper) {
      component.set("v.ShowModule", false);
   },
    
    showfiledata :  function (component, event, helper){
        
        var fileInput = component.find("file").getElement();
        var file = fileInput.files[0];
        if (file) {
        component.set("v.ShowModule", true);
        console.log("File");
        var reader = new FileReader();
        reader.readAsText(file, "UTF-8");
        reader.onload = function (evt) {
            var csv = evt.target.result;
            var table = document.createElement("table");
                    var rows = csv.split("\n");
                    for (var i = 0; i < rows.length; i++) {
                        var cells = rows[i].split(",");
                        if (cells.length > 1) {
                            var row = table.insertRow(-1);
                            for (var j = 0; j < cells.length; j++) {
                                var cell = row.insertCell(-1);
                                cell.innerHTML = cells[j];
                            }
                        }
                    }
                    var dvCSV = document.getElementById("dvCSV");
                    dvCSV.innerHTML = "";
                    dvCSV.appendChild(table);
        }
        reader.onerror = function (evt) {
            console.log("error reading file");
        }
    }
    }
    
    
})

===============================

JS Helper  and Apex Class has no changes same from my above post.

===============================

Thanks,
Maharajan.C


 
rishabh rathor 18rishabh rathor 18
Hi Maharajan.C,
Requirement is Modal Box should Not open as pop up . it should open as static when i choose file. is it possible?
help me
 
rishabh rathor 18rishabh rathor 18
User-added imageSomeThing Like its...
 
Maharajan CMaharajan C
Hi Rishabh,

Use the below changes:


Component :

<aura:component controller="UploadAccountfromLEX" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global">
    
    <aura:attribute name="ShowModule" type="boolean" default="false"/>
    <aura:attribute name="showcard" type="boolean" default="false"/>

    <div>
        <input type="file" class="file" aura:id="file" onchange="{!c.showfiledata}"/>
        <ui:button label="Create Accounts" press="{!c.CreateRecord}"/>
    </div>
    
    <aura:if isTrue = "{!v.showcard}">
         <lightning:card>
            <div id="divCSV">
            </div>  
        </lightning:card>
    </aura:if>
    
</aura:component>

JS Controller:
({
    CreateRecord: function (component, event, helper) {
        var fileInput = component.find("file").getElement();
        var file = fileInput.files[0];
        alert(file);
        if (file) {
        console.log("File");
        var reader = new FileReader();
        reader.readAsText(file, "UTF-8");
        reader.onload = function (evt) {
            
            console.log("EVT FN");
            var csv = evt.target.result;
            console.log('@@@ csv file contains'+ csv);
            var result = helper.CSV2JSON(component,csv);
            console.log('@@@ result = ' + result);
            //console.log('@@@ Result = '+JSON.parse(result));
            helper.CreateAccount(component,result);
            
        }
        reader.onerror = function (evt) {
            console.log("error reading file");
        }
    }

    },
    
    showfiledata :  function (component, event, helper){
        
        var fileInput = component.find("file").getElement();
        var file = fileInput.files[0];
        if (file) {
        component.set("v.showcard", true);
        console.log("File");
        var reader = new FileReader();
        reader.readAsText(file, "UTF-8");
        reader.onload = function (evt) {
            var csv = evt.target.result;
            var table = document.createElement("table");
                    var rows = csv.split("\n");
                    for (var i = 0; i < rows.length; i++) {
                        var cells = rows[i].split(",");
                        if (cells.length > 1) {
                            var row = table.insertRow(-1);
                            for (var j = 0; j < cells.length; j++) {
                                var cell = row.insertCell(-1);
                                cell.innerHTML = cells[j];
                            }
                        }
                    }
                    var divCSV = document.getElementById("divCSV");
                    divCSV.innerHTML = "";
                    divCSV.appendChild(table);
        }
        reader.onerror = function (evt) {
            console.log("error reading file");
        }
    }
    }
    
    
})


Thanks,
Maharajan.C
 
rishabh rathor 18rishabh rathor 18
CAN WE INSERT SELECTED RECORDS IN BY THIS COMPONENT.
THANKS..
 
venkata mani tejavenkata mani teja
how to use lightning fileupload and create Records From uploaded Csv File
Anusha V 47Anusha V 47
Hi Maharajan,

Can you help me with the test class for the code you shared first please ..

thanks in advance.
Salesforce CodesSalesforce Codes
Best answer for your requirement
Import & Export data from CSV file using Lightning Component

User-added image

http://salesforcecodes.com/import-export-data-from-csv-file-using-lightning-component/ (http://salesforcecodes.com/import-export-data-from-csv-file-using-lightning-component/" target="_blank)


 here am going to show you, how to import the data and export the data from csv file using lightning component.
HarshadaHarshada
Can anyone please guide, I want to insert opportunities to their related account using csv.
NK@BITNK@BIT
Salesforce LWC: Upload Task using CSV files (https://nitinkhunalsalesforce.wordpress.com/2021/04/10/salesforce-lwc-upload-task-using-csv-files/)

I have used the CSV file to upload the Task record, you can change the logic for the opportunity object