READ AND INSERT RECORDS FROM A CSV FILE - USING VISUALFORCE / STATIC RESOURCE

Most of them have a requirement to update or insert records from .csv file with apex.

Here is the example solution. We can do it in two ways one is creating static resource for csv and call this csv into you apex and the second way is using your visualforce page.

Step1: Upload the file into Static Resources with the name "Contactsload". / Using visualforce

public class FileUploader 
{
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    String[] filelines = new String[]{};
    List<Contact> conload;
    
    /***This function reads the CSV file and inserts records into the Account object. ***/
    public Pagereference ReadFile()
    {
        try{
                //Convert the uploaded file which is in BLOB format into a string
                nameFile =blobToString( contentFile,'ISO-8859-1'); // If you want are using static resource file do query resorce table and pass the name here
                
                //Now sepatate every row of the excel file
                filelines = nameFile.split('\n');
                
                //Iterate through every line and create a Account record for each row
                conload = new List<Contact>();
                for (Integer i=1;i<filelines.size();i++)
                {
                    String[] inputvalues = new String[]{};
                    inputvalues = filelines[i].split(',');
                    
                    Contact c = new Contact();
                    c.Name = inputvalues[0];
                    c.Email= inputvalues[1];       
                    c.Fax= inputvalues[2];
                    c.Phone= inputvalues[3];
                    c.Mobile = inputvalues[4];
                            
                    conload.add(c);
                }
         }
         catch(Exception e){
                 ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured reading the CSV file'+e.getMessage());
                ApexPages.addMessage(errormsg);
         }       
        //Finally, insert the collected records
        try{
            insert conload;
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured inserting the records'+e.getMessage());
            ApexPages.addMessage(errormsg);
        }    
        return null;
    }
   
   /**** This function sends back to the visualforce page the list of account records that were inserted ****/ 
    public List<Contact> getuploadedContactss()
    {
        if (conload!= NULL)
            if (conload.size() > 0)
                return conload;
            else
                return null;                    
        else
            return null;
    }  
        /**
         This function convers the input CSV file in BLOB format into a string
        @param input    Blob data representing correct string in @inCharset encoding
        @param inCharset    encoding of the Blob data (for example 'ISO 8859-1')
     */
    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);
    }         

}

Visualforce:

<apex:page sidebar="false" controller="FileUploader" showHeader="false">
   <apex:form >
      <apex:sectionHeader title="Upload data from CSV file"/>
      <apex:pagemessages />
      <apex:pageBlock >
             <!--  Component to allow user to upload file from local machine -->
             <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: Use the standard template to upload Contacts. <a href="https://drive.google.com/file/d/0B5FQvDdE4z0PdFllT1g0aGNBN1k/view?usp=sharing" target="_blank"> Click here </a> to download the template. </b> </font>
             </center>  
      
      <!-- After the user clicks the 'Upload File' button, this section displays the inserted data -->
      
      <apex:pageblocktable value="{!uploadedContacts}" var="con" rendered="{!NOT(ISNULL(uploadedContacts))}">
          <apex:column headerValue="Contact Name">
              <apex:outputField value="{!con.Name}"/>
          </apex:column>
          <apex:column headerValue="Email">
              <apex:outputField value="{!con.Email}"/>
          </apex:column>
          <apex:column headerValue="Fax">
              <apex:outputField value="{!con.Fax}"/>
          </apex:column>
          <apex:column headerValue="Phone">
              <apex:outputField value="{!con.Phone}"/>
          </apex:column>
 <apex:column headerValue="Mobile">
              <apex:outputField value="{!con.Mobile}"/>
          </apex:column>
          
      </apex:pageblocktable> 
      
      </apex:pageBlock>       
   </apex:form>   

</apex:page>

Post a Comment

0 Comments