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
sooraj kesavadassooraj kesavadas 

uploading records from csv to custom object

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
Raj VakatiRaj Vakati
Hi Sooraj,
Can you remove remove  white apces and try as shown below   . Make sure the your csv table fomrat is correct . 

couObj.Contact__c = csvRecordData[2].deleteWhitespace();
 
sooraj kesavadassooraj kesavadas
Hi Rajamohan, I tried your suggestion but I am still getting the same error.
Raj VakatiRaj Vakati
Hi ,
Can you pass your error message here? 
sooraj kesavadassooraj kesavadas
When I try to upload the csv file as it is, I get the error "An error has occured while importing data. Please make sure input csv file is correct
" , which is the custom error message in the catch block. But if I catch the exception e and do a System.debug(e.getMessage()),then in the debug log, it says that "Invalid Id:1256", where 1256 is the id of the record I am trying to insert. If I remove all the reference about Id, I get "Invalid date: 6/20/2017". Only if I remove all the reference of id and date, I can insert the record.
Raj VakatiRaj Vakati
Hi Sooraj , 
1. You no need to insert the record . Salesorce will do it for you . Take the ID out from csv 
2 . Go to the data colums in CSV , update the formate to to date . No to the text  . Here is the date format you can choose 
The following date formats are also supported:
yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
yyyy-MM-dd'T'HH:mm:ss.SSS Pacific Standard Time
yyyy-MM-dd'T'HH:mm:ss.SSSPacific Standard Time
yyyy-MM-dd'T'HH:mm:ss.SSS PST
yyyy-MM-dd'T'HH:mm:ss.SSSPST
yyyy-MM-dd'T'HH:mm:ss.SSS GMT-08:00
yyyy-MM-dd'T'HH:mm:ss.SSSGMT-08:00
yyyy-MM-dd'T'HH:mm:ss.SSS -800
yyyy-MM-dd'T'HH:mm:ss.SSS-800
yyyy-MM-dd'T'HH:mm:ss
yyyy-MM-dd HH:mm:ss
yyyyMMdd'T'HH:mm:ss
yyyy-MM-dd
MM/dd/yyyy HH:mm:ss
MM/dd/yyyy





Here is the code for you 
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[1] ;  
           //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);
    }  
}




 
sooraj kesavadassooraj kesavadas
Hi, Thanks for the reply. I removed the Id from the csv file and changed the format of date column from text to Date. But now I am getting  "Invalid Date: 6/1/2017" error.
Raj VakatiRaj Vakati
Update this line  
couObj.Course_Date__c = Date.parse(String.valueOf(temp_date); 

 
Raj VakatiRaj Vakati
couObj.Course_Date__c = Date.parse(String.valueOf(temp_date)); 
sooraj kesavadassooraj kesavadas
Hey Rajamohan, 

I am still getting the same error about the date. BTW it's really cool of you of you to give me suggestions and for helping me like this. Thank you very much
Kunal BorseKunal Borse
@sooraj kesavadas.... Tyr that one
if you have get invalid date first you need to create method that one i will shown in below and call it in importCSVFile method

 add this poc in your importCSVFile(){
date courseDate=importDataFromCSVController.getSortedDate(csvRecordData[4]);
conObj.Course_Date__c = courseDate;
}


public static date getSortedDate(String Dt ){
        List<String> tempArray = Dt.split('-');
        Date dnew=Date.newInstance(integer.valueOf(tempArray[2]), integer.valueOf(tempArray[1]), integer.valueOf(tempArray[0])); 
        system.debug('dnew-------------------->'+dnew);
        return dnew;
    }