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:pageBlock >
           <apex:pageblocktable value="{!sObjectList}" var="rec">
              <apex:column value="{!}" />
              <apex:column value="{!rec.AccountNumber}" />
              <apex:column value="{!rec.Accountsource}" />
              <apex:column value="{!rec.Type}" />
              <apex:column value="{!rec.Website}" />

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(','))
       for(Integer i=1;i<csvfilelines.size();i++){
           Account accRec = new Account() ;
           string[] csvRecordData = csvfilelines[i].split(',');
  = csvRecordData[0] ;            
           accRec.accountnumber = csvRecordData[1];
           accRec.Type = csvRecordData[2];
  = csvRecordData[3];
           accRec.AccountSource = csvRecordData[4];                                                                              

Output :


Post a Comment

| ,