Salesforce | Read csv file, insert objects and get results back in Apex visualforce page

Author - Shalini

If you have a csv file with raw data and you want to read it using apex, convert to sfdc objects and insert these, then get success and failure results back then following steps and code can help you:

1. Create an Apex Class which will read the CSV file:

*This function reads the CSV file and inserts records into the Contact object. ***/
 public Pagereference ReadFile()
  {
   try{
      //Convert the uploaded file which is in BLOB format into a string
      nameFile =blobToString( contentFile,'ISO-8859-1');
      //Now separate every row of the excel file
      fileLines = nameFile.split('n');
      //Iterate through every line and create a Contact record for each row
      contactsToUpload = new List();
      for (Integer i=1;i<fileLines.size();i++) { String[] inputvalues = new String[]{}; inputvalues = fileLines[i].split(','); Contact c = new Contact(); c.FirstName = inputvalues[0]; c.FirstName = inputvalues[0]; c.ShippingStreet = inputvalues[1]; c.ShippingCity = inputvalues[2]; c.ShippingState = inputvalues[3]; c.ShippingPostalCode = inputvalues[4]; c.ShippingCountry = inputvalues[5]; contactsToUpload.add(c); } } catch(Exception e){ ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured reading the CSV file'+e.getMessage()); ApexPages.addMessage(errormsg); } //Finally, insert the collected records try{ insert contactsToUpload; } catch (Exception e) { ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occurred inserting the records'+e.getMessage()); ApexPages.addMessage(errormsg); } return null; } /** This function converts the input CSV file in BLOB format into a string @param input Blob data representing correct string in @inCharset encoding @param inCharset encoding of the Blob data (for example 'ISO 8859-1') */ public static String blobToString(Blob input, String inCharset){ String hex = EncodingUtil.convertToHex(input); System.assertEquals(0, hex.length() & 1); final Integer bytesCount = hex.length() >> 1;
      String[] bytes = new String[bytesCount];
      for(Integer i = 0; i < bytesCount; ++i)
      bytes[i] =  hex.mid(i << 1, 2);
      return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    }
}

2. If you want to display success as well as error records/ messages on the page then use Database.SaveResult method:

Database.SaveResult[] srList = Database.insert(contactsToUpload, false);
//**Iterate through  returned result and get success and fail results:
for (Database.SaveResult sr : srList) {
   if (sr.isSuccess()) {
   // Operation was successful, so get the ID of the record that was processed
   System.debug('Successfully inserted account. Account ID: ' + sr.getId());
   }
   else {
    // Operation failed, so get all errors
    for(Database.Error err : sr.getErrors()) {
    System.debug('The following error has occurred.');
    System.debug(err.getStatusCode() + ': ' + err.getMessage());
    System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *