Import CSV file In Salesforce using Apex

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

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

Below is the code snippet which import CSV file from apex.

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.

 

Articles :

https://developer.salesforce.com/page/Paginating_Data_for_Force.com_Applications

https://help.salesforce.com/articleView?id=000233560&type=1

 

Thanks

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s