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
Puneeth KumarPuneeth Kumar 

Reading Ids from CSV for using in SOQL where clause.

Hi All,

I have a requirement where given the list of account Ids in CSV file and all related contacts under those accounts need to be extracted in CSV. For this I want to query all the contact with (Select ID,Name from contacts where Account.ID IN: [Read from csv file]) , or simple parsing the list of IDs from csv file to a variable and then querying on that variable. Can anyone help me out in how to achieve this through apex code.

Thank you.
Nayana KNayana K
Refer this link : http://sfdcsrini.blogspot.com/2014/04/how-to-read-csv-file-from-apex_17.html

You can refer below sample :

// Assuming in CSV file's  first column contains Account Ids
public class FileUploader 
{
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    String[] filelines = new String[]{};
    List<Contact> lstContactToDisplay = new List<Contact>();
    
    public Pagereference ReadFile()
    {
        nameFile=contentFile.toString();
        filelines = nameFile.split('\n');
        Set<Id> setIdAcc = new Set<Id>();
        for (Integer i=1;i<filelines.size();i++)
        {
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
            
            setIdAcc.add(inputvalues[0]);
           
        }
        try{
               lstContactToDisplay = [SELECT Id, Name FROM Contact WHERE AccountId IN: setIdAcc];
               // Do the necessary logic now 
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
            ApexPages.addMessage(errormsg);
        }    
        return null;
    }
    
}


<apex:page sidebar="false" controller="FileUploader">
   <apex:form >
      <apex:sectionHeader title="Upload data from CSV file"/>
      <apex:pagemessages />
      <apex:pageBlock >
             <center>
              <apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
              <br/> <br/> <font color="red"> <b>Note: Please use the standard template to upload Accounts.</b> </font>
             </center>  
      
      
     
      
      </apex:pageBlock>       
   </apex:form>   

</apex:page>
 
Puneeth KumarPuneeth Kumar
Thanks Nayana, thats so helpful. 
Nayana KNayana K
Please mark this as solved so that it may help others.