+ Start a Discussion
Soundar Raj PonpandiSoundar Raj Ponpandi 

Update Existing records by Upload CSV File

Hi Expert,

I Have One Requirement,

1. Want to update Sales_Order__c record's (going to update Sap_Number__c , SAP_createdDate__c). 

2.Click to Upload Excel File.

3. Click to Update Sales Order Button .

4.Need To Updae With Existing Records (With same Rcords).

5. I designed a  Visualforce pages as well, please give me a good idea to how can i achieve this Process with the Apex.


Regards,
Soundar.
Best Answer chosen by Soundar Raj Ponpandi
Soundar Raj PonpandiSoundar Raj Ponpandi
Hi ,

Finally I achieve This Process By Following Way ... Thanks For Your Valuable Suggestion

@Controller
 
public class UpdateSapDetailsForSpare {
    
    public List<Sales_Order__c> solist{get;set;}
    Public Blob contentFile{get;set;}
    Public String AsString{get;set;}
    String[] FileLines = New String[]{};
    public list<wrapper> wrapList = New list<wrapper>();
    Public list<wrapper> getWrapList(){
        return wrapList;
    }
    Map<String,Wrapper> wrapMap = new Map<String,Wrapper>();
    Set<String> adWrp = new Set<String>();
    List<Sales_Order__c> soList1= New List<Sales_Order__c>();
    Public Boolean Success{get;Set;}
    Public Boolean page1{GET;SET;}
    Public Boolean page2{GET;SET;}
    
    public UpdateSapDetailsForSpare(){
        FileLines = new String[]{};
            solist = New List<Sales_Order__c>();
        page1 = True;
    }
    
    public void importSapDataFromCSVController(){
         //Savepoint sp;  
         //ge1 = False;
        page2 = true;
         
        Try{
            //sp = Database.setSavepoint();
            //Success = True; 
            if(contentFile != null){
                System.debug('File Size | ' + contentFile.size());
                System.debug('File Size | ' + contentFile.size());
                AsString = blobToString(contentFile,'ISO-8859-1');  //contentFile.toString();
                FileLines= AsString.split('\n');
                system.debug('FileLines Size | ' + FileLines);
            for(Integer i=1;i<FileLines.size();i++){
                Wrapper wrap = new Wrapper();
                string[] csvRecordData = FileLines[i].split(',');
                System.debug('csvRecordData | ' + csvRecordData);
                wrap.SONumber = csvRecordData[0];
                wrap.SapNo = csvRecordData[1];
                wrap.SapDate = csvRecordData[2];
                //SOrder.SO_Date__c = Date.valueOf(csvRecordData[1]);
                
                wrapList.add(wrap);
                System.debug('wrapList | ' + wrapList);
                wrapMap.put(wrap.SONumber, wrap);
                System.debug('WrapMap | ' + wrapMap);
                adWrp.add(wrap.SONumber);
                System.debug('AddWrap | ' + adWrp);   
            }
         }
      }
        catch (Exception e)
        {
            System.debug(e.getMessage() + ' | ' +  e.getLineNumber());
        }  
    }
    
    
    public PageReference UpdateSapDataFromCSVController(){
        IF(adWrp.size() > 0){
        System.debug('adWrp.size() | ' + adWrp.size());
        For(Sales_Order__c sord : [SELECT id,Name,SAP_SO_No__c,SO_Date__c FROM Sales_Order__c WHERE Name =:adWrp]){
            System.debug('Sales Order |  ' + sord);
            System.debug('SalesOrder ContainsKey|  ' + wrapMap.containsKey(sord.Name));
            IF(wrapMap.containsKey(sord.Name)){
                sord.SO_Date__c = Date.valueOf(wrapMap.get(sord.Name).SapDate);
                sord.SAP_SO_No__c = wrapMap.get(sord.Name).SapNo;
                soList1.add(sord);
            }
            
        }
        }
        system.debug('SoList | ' + soList1.size());
        IF(soList1.size() > 0){
            update soList1;
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.severity.Confirm, 'Sales Order updated Successfully');
            ApexPages.addMessage(myMsg); 
        }
        //PageReference pageRef = new PageReference('https://lightening--pcsb--c.cs57.visual.force.com/apex/Update_Sap_Details_For_Spare?core.apexpages.request.devconsole=1');
        Return null;
    
  }  
    /* Wrapper Class */
    public class wrapper{
        public String SONumber{get;set;}
        Public String SapNo{get;set;}
        Public String SapDate{get;set;}
        
    } 
    
     public static String blobToString(Blob input, String inCharset){
        
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
            bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    } 
    
    
}

Regards,

Soundar.​

All Answers

Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Soundar Raj,

Data Import Wizard to update records.May I suggest you please refer the below link for reference. Hope it will be helpful.

Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.

Thanks
Rahul Kumar

 
NagendraNagendra (Salesforce Developers) 
Hi Anil,

Import CSV file using apex visual force:

Normally we use Apex data loader to import data in Salesforce from CSV file. Nowadays some other tools are also available to load data in Salesforce like Jitterbit data loader. But sometimes there is a requirement when end users do not want to use Apex Data loader. They want some custom page to load data in Salesforce. Then, in that case, we can use custom code to load data in Salesforce from a CSV(http://www.sfdcpoint.com/salesforce/import-csv-file-using-apex-visualforce/) file.

Also sometimes using single CSV file we want to load data in multiple objects. Then, in that case, we can not use data loader to load data. In that case, we can use custom code to load data in Salesforce.

In the example below, we are loading data from CSV file for account objects.
First of all, we need CSV file format. Click here to download CSV file. You can modify CSV file to insert or import account records. CSV file attached has the following format:

User-added image

Now we need to write code in Apex and visual force which will read a CSV file and insert records in account object.

Click on choose file, then select a CSV file and then click on ‘Import Account’ button. All records from CSV file will be inserted on account records. I have commented insert account line. So this example will only show account records on a visual force page. You can uncomment insert account list line in below code if you want to insert account list.

User-added image

"May I suggest you please check with sample code below which will insert records using apex and visual force and streak it as per your requirement which will point you in the right direction."

Visual Force Page:
<apex:page controller="importDataFromCSVController">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="4"> 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Import Account" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accList}" var="acc">
              <apex:column value="{!acc.name}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Accountsource}" />
              <apex:column value="{!acc.Industry }" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>
Apex Controller:
public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<account> acclist{get;set;}
  public importDataFromCSVController(){
    csvFileLines = new String[]{};
    acclist = New List<Account>(); 
  }
  
  public void importCSVFile(){
       try{
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n'); 
            
           for(Integer i=1;i<csvFileLines.size();i++){
               Account accObj = new Account() ;
               string[] csvRecordData = csvFileLines[i].split(',');
               accObj.name = csvRecordData[0] ;             
               accObj.accountnumber = csvRecordData[1];
               accObj.Type = csvRecordData[2];
               accObj.AccountSource = csvRecordData[3];   
               accObj.Industry = csvRecordData[4];                                                                             
               acclist.add(accObj);   
           }
        //insert acclist;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importin data Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}
For more information please check with below links.
Hope this helps.

Kindly mark this as solved if it's resolved.

Thanks,
Nagendra


 
Soundar Raj PonpandiSoundar Raj Ponpandi
Hi Nagendra,

Hearty thanks for your quick response.

As per your suggestion a record can be insert. Can you please show sample code how can i update a records.

1. Initially i have export Sales Orders from Salesfroce.

2. After That i have maken few changes in this excell by uploading in SAP (......In Another Org).

3.After that i have import modified excel into salesforce. (Same Data is there in salesforce, Now i am going to update modified records into existing records) , two fields only will be  going to change .


Note :  I want to update through the visualforce page only. So only i avoided Standard Import & Export Tools Like import Wizard, Data loader , Etc...


Regards,

Soundar
Soundar Raj PonpandiSoundar Raj Ponpandi
Hi Rahul Kumar ,

Really Thanks For your quick response... i want to update the records by using  the visualforce page only. Please give me good solution.


Regards,
Soundar. 
Soundar Raj PonpandiSoundar Raj Ponpandi
Hi ,

Finally I achieve This Process By Following Way ... Thanks For Your Valuable Suggestion

@Controller
 
public class UpdateSapDetailsForSpare {
    
    public List<Sales_Order__c> solist{get;set;}
    Public Blob contentFile{get;set;}
    Public String AsString{get;set;}
    String[] FileLines = New String[]{};
    public list<wrapper> wrapList = New list<wrapper>();
    Public list<wrapper> getWrapList(){
        return wrapList;
    }
    Map<String,Wrapper> wrapMap = new Map<String,Wrapper>();
    Set<String> adWrp = new Set<String>();
    List<Sales_Order__c> soList1= New List<Sales_Order__c>();
    Public Boolean Success{get;Set;}
    Public Boolean page1{GET;SET;}
    Public Boolean page2{GET;SET;}
    
    public UpdateSapDetailsForSpare(){
        FileLines = new String[]{};
            solist = New List<Sales_Order__c>();
        page1 = True;
    }
    
    public void importSapDataFromCSVController(){
         //Savepoint sp;  
         //ge1 = False;
        page2 = true;
         
        Try{
            //sp = Database.setSavepoint();
            //Success = True; 
            if(contentFile != null){
                System.debug('File Size | ' + contentFile.size());
                System.debug('File Size | ' + contentFile.size());
                AsString = blobToString(contentFile,'ISO-8859-1');  //contentFile.toString();
                FileLines= AsString.split('\n');
                system.debug('FileLines Size | ' + FileLines);
            for(Integer i=1;i<FileLines.size();i++){
                Wrapper wrap = new Wrapper();
                string[] csvRecordData = FileLines[i].split(',');
                System.debug('csvRecordData | ' + csvRecordData);
                wrap.SONumber = csvRecordData[0];
                wrap.SapNo = csvRecordData[1];
                wrap.SapDate = csvRecordData[2];
                //SOrder.SO_Date__c = Date.valueOf(csvRecordData[1]);
                
                wrapList.add(wrap);
                System.debug('wrapList | ' + wrapList);
                wrapMap.put(wrap.SONumber, wrap);
                System.debug('WrapMap | ' + wrapMap);
                adWrp.add(wrap.SONumber);
                System.debug('AddWrap | ' + adWrp);   
            }
         }
      }
        catch (Exception e)
        {
            System.debug(e.getMessage() + ' | ' +  e.getLineNumber());
        }  
    }
    
    
    public PageReference UpdateSapDataFromCSVController(){
        IF(adWrp.size() > 0){
        System.debug('adWrp.size() | ' + adWrp.size());
        For(Sales_Order__c sord : [SELECT id,Name,SAP_SO_No__c,SO_Date__c FROM Sales_Order__c WHERE Name =:adWrp]){
            System.debug('Sales Order |  ' + sord);
            System.debug('SalesOrder ContainsKey|  ' + wrapMap.containsKey(sord.Name));
            IF(wrapMap.containsKey(sord.Name)){
                sord.SO_Date__c = Date.valueOf(wrapMap.get(sord.Name).SapDate);
                sord.SAP_SO_No__c = wrapMap.get(sord.Name).SapNo;
                soList1.add(sord);
            }
            
        }
        }
        system.debug('SoList | ' + soList1.size());
        IF(soList1.size() > 0){
            update soList1;
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.severity.Confirm, 'Sales Order updated Successfully');
            ApexPages.addMessage(myMsg); 
        }
        //PageReference pageRef = new PageReference('https://lightening--pcsb--c.cs57.visual.force.com/apex/Update_Sap_Details_For_Spare?core.apexpages.request.devconsole=1');
        Return null;
    
  }  
    /* Wrapper Class */
    public class wrapper{
        public String SONumber{get;set;}
        Public String SapNo{get;set;}
        Public String SapDate{get;set;}
        
    } 
    
     public static String blobToString(Blob input, String inCharset){
        
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
            bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    } 
    
    
}

Regards,

Soundar.​
This was selected as the best answer
Gug ChilGug Chil
You split the row by comma (,) but what if any record in the row contains comma!? the result will be wrong!!
Mahesh MMahesh M
Hi Nagendra  ,

Unable to upload morethan 5MB file through LWC to Salesforce file object . Can you please help me?

Thanks,