Thursday, April 17, 2014

How to Read CSV file from Apex?

How to Read CSV file from Apex display in visualforce?



I recently had to develop a Visualforce page that allowed a Salesforce user to upload a CSV file and then generate some records from the parsed values. Yes, I know that is what the Data Loader is for, but the intended user here was not technically adept. And I thought it was an interesting experiment.




Visualforce page: csvuploadVF

<apex:page sidebar="false" controller="FileUploader">
   <apex:form >
      <apex:sectionHeader title="Upload data from CSV file"/>
      <apex:pagemessages />
      <apex:pageBlock >
             <center>
              <apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
              <br/> <br/> <font color="red"> <b>Note: Please use the standard template to upload Accounts.</b> </font>
             </center>  
      
      
      <apex:pageblocktable value="{!uploadedAccounts}" var="acc" rendered="{!NOT(ISNULL(uploadedAccounts))}">
          <apex:column headerValue="Account Name">
              <apex:outputField value="{!acc.Name}"/>
          </apex:column>
          <apex:column headerValue="Shipping Street">
              <apex:outputField value="{!acc.ShippingStreet}"/>
          </apex:column>
          <apex:column headerValue="Shipping City">
              <apex:outputField value="{!acc.ShippingCity}"/>
          </apex:column>
          <apex:column headerValue="Shipping State">
              <apex:outputField value="{!acc.ShippingState}"/>
          </apex:column>
          <apex:column headerValue="Shipping Postal Code">
              <apex:outputField value="{!acc.ShippingPostalCode}"/>
          </apex:column>
          <apex:column headerValue="Shipping Country">
              <apex:outputField value="{!acc.ShippingCountry}"/>
          </apex:column>
      </apex:pageblocktable> 
      
      </apex:pageBlock>       
   </apex:form>   

</apex:page>


Apex Class:


public class FileUploader 

{
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    String[] filelines = new String[]{};
    List<Account> accstoupload;
    
    public Pagereference ReadFile()
    {
        nameFile=contentFile.toString();
        filelines = nameFile.split('\n');
        accstoupload = new List<Account>();
        for (Integer i=1;i<filelines.size();i++)
        {
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
            
            Account a = new Account();
            a.Name = inputvalues[0];
            a.ShippingStreet = inputvalues[1];       
            a.ShippingCity = inputvalues[2];
            a.ShippingState = inputvalues[3];
            a.ShippingPostalCode = inputvalues[4];
            a.ShippingCountry = inputvalues[5];

            accstoupload.add(a);

        }
        try{
        insert accstoupload;
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
            ApexPages.addMessage(errormsg);
        }    
        return null;
    }
    
    public List<Account> getuploadedAccounts()
    {
        if (accstoupload!= NULL)
            if (accstoupload.size() > 0)
                return accstoupload;
            else
                return null;                    
        else
            return null;
    }            

}


Finally then try to upload the sample file as below with CSV file format.








That's it !!!!!

6 comments:

Unknown said...

Hi,

In my case I am getting the filelines size as 1. so it's not going through the for loop.

nameFile=contentFile.toString();
filelines = nameFile.split('\n');

I am trying this with a custom object.

Unknown said...

Hello Hi,

Thanks for the article posted.

you are trying to parse the values into the salesforce by using column numbers from csv file. But I am looking to check with the column names and need to upload data into salesforce using csv files.

Because the csv file will not be in a fixed format and will keep on changing in my org.How can i parse using strings?

Please suggest.

Thanks,
Naga

Gurgen said...

No way! your data may contain commas, and the code will fail!

Common Writer said...

I'm not able to upload csv with more than 40 rows. Salesforce throws connection refused exception. Any work around to import more than 1000 rows?

Common Writer said...

I'm not able to upload csv with more than 40 rows. Salesforce throws connection refused exception. Any work around to import more than 1000 rows?

pankaj said...

how to read csv which is stored in salesforce custom object under attacment

Post a Comment

 
| ,