Parsing CSV files in Apex

Nonprofiteering, SalesForce on September 12th, 2009 4 Comments

In my grousing about the lack of easy CSV parsing in Apex, I began to feel like Paul Rudd’s character in Web Hot American Summer. Usually it’s not something you would need to do in SalesForce – the Import Wizard or Data Loader are built to do this easily for one table at a time.

I needed to build a widget that would operate on data in potentially 5 tables simultaneously, hence the consternation. Well, it wasn’t all that hard to roll my own. The code sample below (edit: code plugin seems to have died at some point, code is here) does not handle newline characters in the cells/fields, but should do fine dealing with commas and double quotes.  I even got to leave the computer for a precious few seconds to sketch it out on the whiteboard:

csv on the whiteboard

Tags: , ,

4 Responses to “Parsing CSV files in Apex”

  1. Marty Y. Chang says:

    Thank you for providing the code sample for parsing a CSV file with Apex.

    http://wiki.developerforce.com/index.php/Code_Samples#Parse_a_CSV_with_APEX

    However, I would like to provide feedback that I don’t think the code correctly handles quote text delimiters, because the function returns a quoted value with the quotes instead of returning just the value.

    For example, take a file with the following contents:

    “My Value”

    The value is returned as ‘”My Value”‘ instead of ‘My Value’.

  2. vanessen says:

    I want to know how to get the data from the csv to the function?

  3. amith says:

    Since the string takes the content from CSv file. it throws limit exceeded exception. So we cant read or upload many records for example 150 at a time in a file. IS there any alterantive where we can read and store it in a temp file like Java and then upload to salesforce.
    Please help if there is any solution for this.

  4. Ehren says:

    Vanessen, you can get the CSV to the function in a number of ways: Upload it to a Document and parse the Document, do a callout to an external web service, or paste the CSV contents into a textarea in a VisualForce page (in a controller member variable’s field).

    Marty, I haven’t tested it but you may be right. You could add a line that looks for fields starting with “, and ending with “, with no ” between. Regex like this? /^”.*”$/. Then chop the first and last character.

    Amith, we used a Document and then read from the Document. Try that?

Leave a Reply