Import csv file using apex visualforce

Import csv file using apex visualforce

Normally we use Apex data loader to import data in salesforce from CSV file. Now a days some other tools are also available to load data in salesforce like Jitterbit data loader. But sometime there is 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 sometime 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 following format:

Import csv file using apex visualforce

Now we need to write code in Apex and visualforce 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 visualforce page. You can uncomment insert account list line in below code if you want to insert account list.

Click for demo

Import csv file using apex visualforce

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 Code:

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);
        }  
  }
}

Permanent link to this article: https://www.sfdcpoint.com/salesforce/import-csv-file-using-apex-visualforce/

24 comments

1 ping

Skip to comment form

    • Guest on April 29, 2014 at 9:58 pm
    • Reply

    is it possible to use this process to update fields on a standard object instead? Are you able to post this process in apex?

    1. Yes., It is possible to use this process to update field on standard object. Its straightforward. This example is using standard object(Account). You can use other standard objects also.This example defines how we can read csv file. After reading csv file you can do whatever you want with csv file content. You can create new records and you can also update records if you have id of record.

        • rahul ks on December 8, 2014 at 2:44 pm
        • Reply

        Can i do the same with a Custom object ? i need to update certain fields in it.

        1. approved

    • Mike Marshall on December 10, 2014 at 4:29 am
    • Reply

    What is the limit of records? I need to upload 1 million through a process like this one.

      • Priti on February 11, 2021 at 2:50 pm
      • Reply

      How to read Lookup fields from CSV? can anyone give code snippet
      I am trying using ID, but its not working out

    • Krishna Bidwai on December 11, 2014 at 12:57 pm
    • Reply

    i am getting error using above snippet ..visualforce error as collection maximum limit 1000

    • Star on March 3, 2015 at 7:30 am
    • Reply

    If one of the fields on the CSV is read only, how would I handle an update to existing records? It’s not allowing me to iterate since it’s read only.

    1. It is very obvious, system will not allow you to update read only field by any mean. You should not add that field in csv file. But if you want to handle that in your code, you can use metadata describe call to check whether field is read only or not.

    • magi 001 on April 11, 2017 at 4:01 pm
    • Reply

    How to upload “.xlsx / xls” data insert in contact object in salesforce

    • SFDC SPT on June 1, 2017 at 5:54 am
    • Reply

    Hi, I am trying to do the same on a custom object but csvFileLines size is coming as 1 even though there are multiple rows in the csv file. because of that it’s not going through the for loop and inserting the records.

    • vishnu bijjula on July 4, 2017 at 7:56 pm
    • Reply

    Hi,
    if I upload 5 K records, this code will fails.

      • kotes on March 9, 2018 at 3:13 pm
      • Reply

      what is the error you received..!

        • Sjain on May 14, 2020 at 3:45 pm
        • Reply

        I am getting time limit exception error with 2 or 3k records.

    • Supriya on May 14, 2020 at 3:37 pm
    • Reply

    I used the above code, but it fails if import more records like 2k or 3k.
    It is giving Time limit Exception.
    Please suggest.

    • Harshada on June 11, 2020 at 4:40 pm
    • Reply

    Hi, I’m trying to upload csv to create opportunities. But I am getting below error:
    FATAL_ERROR System.DmlException: Insert failed. First exception on row 1; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Opportunity Name, Stage, Close Date]: [Opportunity Name, Stage, Close Date]
    Though there is data in [Opportunity Name, Stage, Close Date]. It is showing in debug log also. Please assist.

    • neha on June 16, 2020 at 4:26 pm
    • Reply

    Hi please let me know how to download the error message in csv file

    • Manohar Bisht on July 10, 2020 at 4:34 pm
    • Reply

    How to write test class for above code?

    • Nikhil on August 10, 2020 at 11:02 pm
    • Reply

    How should I display more that 1000 records

    • Sagar on November 4, 2020 at 12:12 pm
    • Reply

    Thanks! This helped a lot!

    • Priti on February 15, 2021 at 12:12 pm
    • Reply

    How to insert DateTime Field value?
    I am trying different formats, everytime it throws error,

    Can anyone help?

    • Gabriel on March 30, 2021 at 7:04 pm
    • Reply

    Thank you very much for sharing, this is super helpful.

    • Sreelatha on April 15, 2021 at 12:20 am
    • Reply

    Can we call this code form Flow?

    • ssv on May 20, 2021 at 5:02 am
    • Reply

    i am getting a no file or empty file error when i send the csv from a particular sending emailID.. i think it’s going out as a read-only or somehow restricted attachment that the apex code is unable to process

  1. […] Import csv file using apex visualforce – … – Import csv file using apex visualforce. Normally we use Apex data loader to import data in salesforce from CSV file. Now a days some other tools are also available to … […]

Leave a Reply

Your email address will not be published.