• Kunal Borse
  • NEWBIE
  • 0 Points
  • Member since 2022

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
I have this requirement to upload the records from a csv file and populate a custom object Course with fields Id, Name, Contact(Lookup detail to Contact Object), Fees and Date using Apex and Visualforce. This is the apex code I have:
public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<Course__c> courlist{get;set;}
public importDataFromCSVController(){
    csvFileLines = new String[]{};
        courlist = New List<Course__c>(); 
}

public void importCSVFile(){
    try{
        csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        for(Integer i=1;i<csvFileLines.size();i++){
            Course__c couObj = new Course__c();
            string[] csvRecordData = csvFileLines[i].split(',');
            couObj.name = csvRecordData[0] ;  
            couObj.id = csvRecordData[1];

            couObj.Contact__c = csvRecordData[2];
            String temp_fees=csvRecordData[3];
            couObj.Course_fees__c = Decimal.valueOf(temp_fees);
            String temp_date=csvRecordData[4];
            couObj.Course_Date__c = Date.parse(temp_date); 

            courlist.add(couObj);   
        }
        insert courlist;
    }
    catch (Exception e)

    {
        System.debug(e.getCause());
        ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importing data. Please make sure input csv file is correct');
        ApexPages.addMessage(errorMessage);
    }  
}

and the Visualforce code :
<apex:page controller="importDataFromCSVController">
<apex:form >
    <apex:pagemessages />
    <apex:pageBlock >
        <apex:pageBlockSection columns="5"> 
              <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
              <apex:commandButton value="Import Account" action="{!importCSVFile}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
    <apex:pageBlock >
       <apex:pageblocktable value="{!courList}" var="cours">
          <apex:column value="{!cours.Id}" />
          <apex:column value="{!cours.Name}" />
          <apex:column value="{!cours.Contact__c}" />
          <apex:column value="{!cours.Course_fees__c}" />
          <apex:column value="{!cours.Course_Date__c}" />
    </apex:pageblocktable>
 </apex:pageBlock>

and the data in the csv file is:
User-added image

When I try to upload this data, I will get the custom error from the Catch block. However if I remove the Id and date field reference from the data as well as from the code, I can successfully upload the data. I am fairly new to coding, so if  someone can point it out to me what I am doing wrong, I would very much appreciate that.

Thanks