Thursday 3 March 2016

Parsing the CSV file in salesforce

Hi Salesforce folks ,

Many times you get a request to parse the contents of csv file and create records in salesforce objects.

In this blog I am going to demonstrate you how the parse the csv file using Apex.

Before starting the Apex code I would like to give you information about csv file

What is a csv file ?

CSV file having records as comma separated values.It stores the tabular data in plain text. Each line in the file is a record.

How the data is structured in the csv file ?
There are various formats of saving data to the csv file for example
"Name", "Address" => Header Row
"Ajay","Pune" => Data
"Ajay","Talegaon,Pune" => You may get data like this : Nested inside the "" with comma(,)

You can just google it for the various formats.

In the below snippet I am parsing the csv file and creating records in the Account salesforce object.

Assumption : You got csv file data in a string format. If you are getting data in blob format then you can convert it to string using string.valueof function.

Pass the string value to the below function and take a cup of tea !!!! :)






You can enhance the above code by adding exception handling of your choice.

Limitation : 
The above code will work for 10000 records.(Standard Salesforce DML Limit).

You can overcome this limit by writing batch class. Send records to batch class for further processing.

Many more blogs are coming soon !!!

Stay connected !!!

Cheers !!

10 comments:

  1. Cool !! Is there any limitation for this method? as in which format of CSV it won't be able to parse?

    ReplyDelete
    Replies
    1. Currently the method is accepting csv file body in string format , So if you are receiving body in blob then you need to convert it to string and send that string to this method.
      if csv comes without "" for data then it will not work , need to add this condition.
      Thanks for feedback !!!

      Delete
    2. Careful with the quotation marks
      if the csv was opened in excel and saved, you will have quotation marks
      if it was a simple export as csv, it will NOT contain quotation marks, especially if this comes from another data base

      Delete
  2. Thank you. Very informative

    ReplyDelete
  3. Hi Ajay great work ...instead putting the image can u please put the code snippet

    ReplyDelete
    Replies
    1. Hi Sangeetha.. Yes I will be adding code snippet from the next blog. I am also planning to share the git repository.

      Delete
    2. It's very helpful..

      Delete
  4. Good Example. thanks Ajay :)

    ReplyDelete
  5. Thanks Ajay. How to write test class for this.

    ReplyDelete