Parsing CSV to sObject using Apex in Salesforce

To parse CSV to sObject using Apex in Salesforce, use the below link to get the code

Cheers !!!

Sample code:

public List<List<String>> parseCSV(String contents,Boolean skipHeaders) 
     List<List<String>> allFields = new List<List<String>>();  
     // replace instances where a double quote begins a field containing a comma  
     // in this case you get a double quote followed by a doubled double quote  
     // do this for beginning and end of a field  

     contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');  

     // now replace all remaining double quotes - we do this so that we can reconstruct  

     // fields with commas inside assuming they begin and end with a double quote  

     contents = contents.replaceAll('""','DBLQT');  

     // we are not attempting to handle fields with a newline inside of them  

     // so, split on newline to get the spreadsheet rows  

     List<String> lines = new List<String>();  


         lines = contents.split('\n');  
     catch (System.ListException e) 
         System.debug('Limits exceeded?' + e.getMessage());  

     Integer num = 0;  

     for(String line : lines)


         // check for blank CSV lines (only commas)  

         if (line.replaceAll(',','').trim().length() == 0) break;             

         List<String> fields = line.split(',');      

         List<String> cleanFields = new List<String>();  

         String compositeField;  

         Boolean makeCompositeField = false;  

         for(String field : fields) 


             if (field.startsWith('"') && field.endsWith('"')) 

             } else if (field.startsWith('"')) 
                 makeCompositeField = true;  
                 compositeField = field;  
             else if (field.endsWith('"')) 
                 compositeField += ',' + field;  
                 makeCompositeField = false;  


             else if (makeCompositeField) 
                 compositeField +=  ',' + field;  


     if (skipHeaders) allFields.remove(0);  

     return allFields;         

Here contents is fileContent.toString(). Where fileContent is the value of file mentioned in <apex:inputFile.>


<apex:inputFile value = "{!fileContent}" name = "{!fileName}"/>


1 comment:

  1. For more than 6000 records this is failing as I am getting Regex is too complicated. It is giving me error after the line .split('\n');


Sharing is Caring!!! Share this with your friends!!!

submit to reddit