Import data using CSV file in visualforce page in salesforce

By | December 9, 2019

Hi guys, here we are going to show you, how to Import data using CSV file in visualforce.

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(){
            csvAsString = csvFileBody.toString();
            csvFileLines = csvAsString.split('\n'); 
            for(Integer i=1;i<csvFileLines.size();i++){
                Account accObj = new Account() ;
                string[] csvRecordData = csvFileLines[i].split(',');
       = csvRecordData[0] ;             
                accObj.accountnumber = csvRecordData[1];
                accObj.Type = csvRecordData[2];
                accObj.AccountSource = csvRecordData[3];   
                accObj.Industry = csvRecordData[4];                                                                             
            insert acclist;
        catch (Exception e)
            ApexPages.Message msg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importing data Please make sure input csv file is correct');

vf 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:pageBlock >
           <apex:pageblocktable value="{!accList}" var="acc">
              <apex:column value="{!}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Accountsource}" />
              <apex:column value="{!acc.Industry }" />


Choose csv file & then click on Import Account

Leave a Reply

Your email address will not be published. Required fields are marked *