Upload Contacts from CSV file in a Visualforce Page - Source: Ranjeet Singh

11:27 AM

Many thanks to Mr.Ranjeet Singh for submitting this article. This article is a sample code which lets you upload contacts from a Visualforce Page using a CSV file...

Click here if you too would like to submit an article for this blog

Step 1:

1) Create the Apex Class: UploadRecordUsingCSVContact
public with sharing class UploadRecordUsingCSVContact {
    
    public Blob FileRecords{get;set;}
    String[] LineNo=new String[]{};
    List<Contact> AllContact;
    Public Pagereference UploadFile()
     {
       String FileData=FileRecords.toString();
       LineNo=FileData.split('\n');
       Allcontact=new List<Contact>();
       for(Integer i=1;i<LineNo.size();i++)
        {
          Contact con=new Contact();
          String[] ActualData=new String[]{};
          ActualData=LineNo[i].split(',');
          con.FirstName=ActualData[0];
          con.LastName=ActualData[1];
          con.Email=ActualData[2];
          con.Phone=ActualData[3];
          Allcontact.add(con);
        }
       try
       {
         insert Allcontact;
       } 
       catch(Exception e) 
        {
        
        }
       return Null;
     }  

Step 2: Create VF Page: UploadRecordUsingCSVContact

<apex:page controller="UploadRecordUsingCSVContact" >
 <apex:form >
  <apex:sectionHeader title="Upload Contact Records uing CSV File"/>
  <apex:pageblock >
    <Center>
        <apex:inputfile value="{!FileRecords}"></apex:inputfile><apex:commandButton value="Upload File" action="{!UploadFile}"/><br/><br/>
        <font color="Red"><b>Note:&nbsp;<a href="{!$Resource.ContactUploadTemplate}" target="__blank">Click Here </a>To download the Format.</b></font>
    </Center>
  </apex:pageblock> 
 </apex:form>
</apex:page>


Step 3:  Create a CSV File and the file must be in the following mentioned Format:
First Name Last Name Email Phone
Ranjeet Singh xxxxx@gmail.com xxxxxxx

1 comments

  1. I guess this creates orphan contacts. Is there a way to associate contacts with specific accounts?

    ReplyDelete