Concepts or coding lessons of Salesforce that you can implement easily

Import CSV file In Salesforce using Apex in 3 Easiest Steps

Salesforce does not read the excel file into apex. To overcome for this either we can covert excel file to CSV and import csv file using below code.

We can import data using data loader But sometime there is requirement when end users do not want to use Apex Data loader. 

Client want custom page to load data in salesforce.

Here I am explaining Import CSV file In Salesforce using Apex. Below is the code snippet which import CSV file from apex. In this blog, I have one visual force page and one controller associated with it. 

Visual force page have Import Accounts into Salesforce button. 
Once user click on the button, I am sending email using apex code. 

Step 1: Go to setup and Create one Apex Controller

public class importDataFromCSVController {

  public Blob csvFileBody{get;set;}
  public String csvAsString{get;set;}
  public String[] csvFileLines{get;set;}
  public List<account> accountlist{get;set;}
  public importDataFromCSVController(){
    csvFileLines = new String[]{};
    accountlist= New List<Account>(); 
  }
  
  public void importCSVFile(){
       try{
             // Read CSV file body and store it in variable
              csvAsString = csvFileBody.toString();
  
            // Split CSV String to lines
             csvFileLines = csvAsString.split('\n'); 
           
            // Iterate CSV file lines and retrieve one column at a time.
             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];                                                                             
               accountlist.add(accObj);   
             }
            // if all correct then insert Account into Org
             if(accountlist.size()>0)
             insert accountlist;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importing data into Salesforce. Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}

Step 2: Create Visual force Page

<apex:page controller="importDataFromCSVController" sidebar="false" showHeader="false">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="4"> 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Import Accounts into Salesforce" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accountlist}" var="acc">
              <apex:column value="{!acc.name}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Phone}" />
              <apex:column value="{!acc.Fax}" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>

Step 3: Download csv file into local machine. Click here to download CSV file. 

CSV will be like:
















Visualforce page have Preview button, you can click on that Preview button. 
OR 
Go to an URL and type or you can paste below URL (Change the salesforceinstancename with your salesforce org URL).

Go to : https://salesforceinstancename/apex/Import_Data_From_CSV .
Load the downloaded CSV file and Click on Import Accounts into Salesforce button

Output:










Note: If the CSV file size are large then you will hit a apex governor limit such as the the 6M byte heap space or the 10 seconds of CPU or the 10,000 rows of DML or the "Regex too complicated" error when importing a large amount of data from a CSV file.

There are other ways to import data into Salesforce.
Check out my other blog: 5 Quick Steps To Install Apex Data Loader.


Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.

Next post: Check out Salesforce Daily Limit Only in 5 Simplest Steps