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
bet accountbet account 

how to upload data to multiple objects from csv file through custom visualforcepage

hai 
 please tell me the code to insert records related to multiple objects with the data from csv file using custom visualforce upload page, you can see preview of my page attached hereUser-added image

Thanks in advance
NagendraNagendra (Salesforce Developers) 
Hi,

Please find the detailed explanation for uploading a CSV file using visual force page.

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 CSV 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.


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

Click on choose file, then select 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 the visualforce page. You can uncomment insert account list line in below code if you want to insert account list.

Visualforce 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);
        }  
  }
}
Mark this as solved if it's resolved so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Thanks,
Nagendra
 
vijayabhaskarareddyvijayabhaskarareddy
Hi@
the below   code for insering records  for account and contact at a time
<apex:page controller="importCSVDataController" sidebar="false">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="4"> 
                  <apex:inputFile value="{!csvBodyData}"  filename="{!csvInString}"/>
                  <apex:commandButton value="Import Account" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accounts}" var="acc">
              <apex:column value="{!acc.name}" />
              
        </apex:pageblocktable>
        
     </apex:pageBlock>
      <apex:pageBlock >
           <apex:pageblocktable value="{!contacts}" var="c">
              <apex:column value="{!c.lastname}" />
              
        </apex:pageblocktable>
        
     </apex:pageBlock>
   </apex:form>
</apex:page>
 
public class importCSVDataController 
{
  public String csvInString{get;set;}
  public Blob csvBodyData{get;set;}
  public String[] readCSVData{get;set;}
  public List<Account> accounts{get;set;}
  public List<Contact> Contacts{get;set;}
  
  public importCSVDataController ()
  {
    readCSVData = new String[]{};
    accounts = New List<Account>(); 
    contacts= new List<contact>();
  }
  
  public void importCSVFile()
  {
       try
       {
           csvInString = csvBodyData.toString();
           System.debug('csvInString='+csvInString);
           readCSVData = csvInString.split('\n'); 
           System.debug('readCSVData='+readCSVData);
            
           for(Integer i=1;i<readCSVData.size();i++)
           {
               Account accObj = new Account() ;
              contact c = new contact() ;
               string[] csvAccountData = readCSVData[i].split(',');
               accObj.name = csvAccountData[0] ;             
               accObj.accountnumber = csvAccountData[1];
               accObj.Type = csvAccountData[2];
               accObj.AccountSource = csvAccountData[3];   
               accObj.Industry = csvAccountData[4];  
               c.lastname=  csvAccountData[0];                                                                         
               accounts.add(accObj); 
               contacts.add(c);  
               
           }
            insert accounts;
            insert contacts;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importing data Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}

 
Victor Nguyen 13Victor Nguyen 13
Hi All,

How can you write the test code for this method?
supriya jain 27supriya jain 27
The code works fine for few records but fails for bulk records , It is giving Time limit exception for 3k records, How can we overcome this error and import lage set of data and update in SFDC