YUCEL
YUCEL

Talking about my Salesforce.com and MuleSoft experience

Edgar Moran
Author

Software Engineer, passionate for tech stuff video and photography, Salesforce and Mulesoft developer

Share


Our Newsletter


Subscribe to get new post notifications.

* indicates required

Tags


Twitter


YUCEL

How to upload a CSV file into Salesforce with apex code

Edgar MoranEdgar Moran

In some scenarios we need to provide users a easy way to upload records or as developer a easy way to execute a bunch of records to do something in our code, so now I'll try to demonstrate how you can upload a simple CSV file with some records inside to Salesforce.

Now first let's create a wrapper class (thinking you wanna have an specific structure of your file) and let's put in there some Contact fields like this

public class CustomContacctInformation{
     public String firstName{get;set;}
     public String lastname{get;set;}
     public String email{get;set;}
}

Then, let's declare some variables that eventually we'll use to handle the incoming data in the CSV file

public Blob csvFileBody{get;set;}//Blob information (info in the file)
public string csvAsString{get;set;}//Variable to transform the blob in a String value
public String[] csvFileLines{get;set;}//Every line contained in our file
public List<CustomContacctInformation> customContactList{get;set;}

So now, we can create the actual method that reads the csv.

public void importCSVFile(){
	customContactList = new List<CustomContacctInformation>();
	csvAsString  = blobToString(csvFileBody,'ISO-8859-1');
		
	//csvFileLines = csvAsString.split('\r');
	csvFileLines = csvAsString.split('\n');
		
	for(Integer i=1;i<csvFileLines.size();i++){
       		
       	     string[] csvRecordData = csvFileLines[i].split(',');  

	     CustomContacctInformation contactInfo_record = new   CustomContacctInformation(); 
	     contactInfo_record.firstName                 = csvRecordData[0];
	     contactInfo_record.lastname                  = csvRecordData[1];
	     contactInfo_record.email                     = csvRecordData[2];

	     customContactList.add(contactInfo_record);
       	}
}

The blobToString method, allow us to ready the Blob variable, some times in mac or windows is not reading the CSV file. Also when I want to split the string information, some times work with "\r" or "\n".

And finally we just need to Create an instance of our wrapper and add the information in the list that we declared previously in order to show it before process it. The whole class look like this

public class moran_CSVReader {
	
	public Blob csvFileBody{get;set;}
	public string csvAsString{get;set;}
	public String[] csvFileLines{get;set;}
	public List<CustomContacctInformation> customContactList{get;set;}

	public moran_CSVReader() {
		csvFileLines = new String[]{};
	}


	public void importCSVFile(){
		customContactList = new List<CustomContacctInformation>();
		csvAsString  = blobToString(csvFileBody,'ISO-8859-1');
		
		//csvFileLines = csvAsString.split('\r');
		csvFileLines = csvAsString.split('\n');
		
		for(Integer i=1;i<csvFileLines.size();i++){
       		
       		string[] csvRecordData = csvFileLines[i].split(',');  

			CustomContacctInformation contactInfo_record = new CustomContacctInformation(); 
			contactInfo_record.firstName                 = csvRecordData[0];
			contactInfo_record.lastname                  = csvRecordData[1];
			contactInfo_record.email                     = csvRecordData[2];

			customContactList.add(contactInfo_record);
       	}
	}

	public static String blobToString(Blob input, String inCharset){
		String hex               = EncodingUtil.convertToHex(input);
		System.assertEquals(0, hex.length() & 1);
		final Integer bytesCount = hex.length() >> 1;
		String[] bytes           = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
            bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    } 

	public class CustomContacctInformation{
		public String firstName{get;set;}
		public String lastname{get;set;}
		public String email{get;set;}
	}
}

And the Visualforce

<apex:page controller="moran_CSVReader">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="4"> 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Import" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
			
			<apex:pageblocktable value="{!customContactList}" var="contact">
				<apex:column value="{!contact.firstName}" />
				<apex:column value="{!contact.lastName}" />
				<apex:column value="{!contact.Email}" />
        	</apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page> 

After that you can implement a save function that loop over your wrapper doing specific actions over the records.

Edgar Moran
Author

Edgar Moran

Software Engineer, passionate for tech stuff video and photography, Salesforce and Mulesoft developer

Comments