Wednesday, September 10, 2014

Data import from csv using Visualforce page

Data import from csv using Visualforce page 

Here is a example to read a csv file and display it in a pageblocktable.

Following example reads a csv file having account records in it and displays them in a table when "Read csv" button is pressed.

Csv file format used in this example:





Visualforce Page:

<apex:page controller="csvFileReaderController">
    <apex:form >  <!-- csv reader demo -->
        <apex:pageBlock >
            <apex:panelGrid columns="2" >
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Read csv" action="{!readcsvFile}"/>
            </apex:panelGrid>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!sObjectList}" var="rec">
              <apex:column value="{!rec.name}" />
              <apex:column value="{!rec.AccountNumber}" />
              <apex:column value="{!rec.Accountsource}" />
              <apex:column value="{!rec.Type}" />
              <apex:column value="{!rec.Website}" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>

Controller Class:

Public with sharing class csvFileReaderController {
public Blob csvFileBody{get;set;}
Public string csvAsString{get;set;}
Public String[] csvfilelines{get;set;}
Public String[] inputvalues{get;set;}
Public List<string> fieldList{get;set;}
Public List<account> sObjectList{get;set;}
  public csvFileReaderController(){
    csvfilelines = new String[]{};
    fieldList = New List<string>();
    sObjectList = New List<sObject>();
  }

  Public void readcsvFile(){
       csvAsString = csvFileBody.toString();
       csvfilelines = csvAsString.split('\n');
       inputvalues = new String[]{};
       for(string st:csvfilelines[0].split(','))
           fieldList.add(st);  
       
       for(Integer i=1;i<csvfilelines.size();i++){
           Account accRec = new Account() ;
           string[] csvRecordData = csvfilelines[i].split(',');
           accRec.name = csvRecordData[0] ;            
           accRec.accountnumber = csvRecordData[1];
           accRec.Type = csvRecordData[2];
           accRec.website = csvRecordData[3];
           accRec.AccountSource = csvRecordData[4];                                                                              
           sObjectList.add(accRec);  
       }
  }
}

Output :







3 comments:

Post a Comment

 
| ,