function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ram dram d 

how to upload excel file data into sales force custom object by using apex( by a cutom button on Custom object)

Hi all,

I need some help in "how to upload excel file data into sales force custom object by using apex( by a cutom button on Custom object)"

Any help much appreaciated !!!

Thanks in Advance
Ram
 
Nubes Elite Technologies Pvt. LtdNubes Elite Technologies Pvt. Ltd
Hi Ram,

You can try the following steps :

Step 1 : Download the template from here (https://drive.google.com/file/d/0B5FQvDdE4z0PdFllT1g0aGNBN1k/view). Save the file in your desktop. Upload the file into Static Resources with the name "TestUploadTemplate".

Step 2 : Create an Apex Class named "FileUploader". Paste the code below and save it.
 
public class FileUploader 
{
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    String[] filelines = new String[]{};
    List<Account> accstoupload;
    
    /***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');
                
                //Now sepatate every row of the excel file
                filelines = nameFile.split('\n');
                
                //Iterate through every line and create a Account record for each row
                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);
                }
         }
         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 accstoupload;
        }
        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<Account> getuploadedAccounts()
    {
        if (accstoupload!= NULL)
            if (accstoupload.size() > 0)
                return accstoupload;
            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);
    }         
}

Step 3 : Create a Visualforce Page named "UploadAccounts". Paste the code below and save it.
 
<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: Please use the standard template to upload Accounts. <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="{!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>


Step 4 : Download the CSV file from here (https://drive.google.com/file/d/0B5FQvDdE4z0PeWdCNTlBV25UYTQ/view) for test method coverage. Upload the file with the name 'testMethodCSVUpload'.

Step 5 : Create an Apex Class as shown below for test coverage if you want to check the code coverage.
 
@IsTest(SeeAllData=true)
private class FileUploader_TestMethod
{

     static testmethod void testfileupload(){
         StaticResource testdoc = [Select Id,Body from StaticResource where name ='testMethodCSVUpload'];
         FileUploader  testUpload = new FileUploader();
         testUpload.contentFile= testdoc.Body;
         testUpload.ReadFile();
         testUpload.getuploadedAccounts();
     }
}



Thank You,
www.nubeselite.com
Development | Training | Consulting

Please mark this as solution if your problem is solved.

 
ram dram d
Hi Nubes Elite Technologies Pvt. Ltd thanks for your reply, actually i need to upload excel file into salesforce but above code is working for only csv files. 
Thomas FolThomas Fol
Skyvia allows users to automatically upload excel data into Salesforce without coding. It is a freemium platform. Read here (https://skyvia.com/data-integration/salesforce-data-loader)