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
jayaram reddyjayaram reddy 

Import excel file using apex visual force

Hi,

I want Import excel file using apex visual froce, please help me , it is urgency task.
NagendraNagendra (Salesforce Developers) 
Hi Jayaram,

Providing the CSV files are not too big, you can use a Visualforce apex:inputFile to upload the file and then apply this Parse a CSV with Apex sample code to grab the data from the rows.

If the CSV files are large you will hit a governor limit(https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_gov_limits.htm) such as the 6M byte heap space or the 10 seconds of CPU or the 10,000 rows of DML.

Import csv file using apex visualforce:

Normally we use Apex data loader to import data in salesforce from CSV file. Now a days some other tools are also available to load data in salesforce like Jitterbit data loader. But sometime there is requirement when end users do not want to use Apex Data loader. They want some custom page to load data in salesforce. Then in that case we can use custom code to load data in salesforce from csv file.

Also sometime using single CSV file we want to load data in multiple objects. Then in that case we can not use data loader to load data. In that case we can use custom code to load data in salesforce.
In the example below we are loading data from CSV file for account objects.
First of all we need CSV file format. Click here to download CSV file. You can modify CSV file to insert or import account records. CSV file attached has following format:
User-added image Now we need to write code in Apex and visualforce which will  read csv file and insert records in account object.
Click on choose file, then select csv file and then click on ‘Import Account’ button. All records from csv file will be inserted on account records. I have commented insert account line. So this example will only show account records on visualforce page. You can uncomment insert account list line in below code if you want to insert account list.

Visual Force Page:
<apex:page controller="importDataFromCSVController">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="4"> 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Import Account" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accList}" var="acc">
              <apex:column value="{!acc.name}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Accountsource}" />
              <apex:column value="{!acc.Industry }" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>
Apex Controller:
public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<account> acclist{get;set;}
  public importDataFromCSVController(){
    csvFileLines = new String[]{};
    acclist = New List<Account>(); 
  }
  
  public void importCSVFile(){
       try{
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n'); 
            
           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];                                                                             
               acclist.add(accObj);   
           }
        //insert acclist;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importin data Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}
Hope this helps.

Please mark this as solved if it's resolved.

Thanks,
Nagendra

 
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Jayaram Reddy,
May I request you to please refer the below link for reference. Hope it will be helpful.

Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.

Thanks
Rahul Kumar
jayaram reddyjayaram reddy
Hi Rahul,
Thanks for reply,

I have refer above links, already i know csv file import process, but i want excel file import process.
Thanks,
Jayaram 
NagendraNagendra (Salesforce Developers) 
Hi Jayaram,

Excel files are tricky, depending on the version of Office used, if your users are using the latest version (.xlsx), you can access the contents, however, if it is the older format (.xls) this is a binary format and is not parseable by Apex. Check out this blog and approach on how to upload a .xlsx file(https://andyinthecloud.com/2012/12/09/handling-office-files-and-zip-files-in-apex-part-2/) and access its contents (which are mostly XML files). The basic idea is this...
<c:unzipfile name="somezipfile" oncomplete="unzipped(state);"
  onreceive="{!$RemoteAction.UnzipDemoController.receiveZipFileEntry}" />
Then to handle the contents of the XLXS file an Apex method is defined as follows...
@RemoteAction
public static String receiveZipFileEntry(String filename, String path, String data, String state)
This is a screenshot from the blog that shows what you can do...

User-added image

Hope this helps.

Mark this as solved if it's resolved.

Thanks,
Nagendra
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Jayaram,

How do I import an Excel spreadsheet into Salesforce ?please refer the below link for reference.
Hope it will be helpful.

Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.

Thanks
Rahul Kumar
Shubha Pradhan 18Shubha Pradhan 18
Hi,

How to export the VF data to excel and send as an attachment in email.

Thanks in Advance