If you search Salesforce Stack Exchange, you'll find at least dozens of examples of lousy Apex CSV parsers: parsers that fail on files with embedded quotes, embedded commas, embedded newlines; parsers that can't handle anything but UTF-8; parsers that blow up if a row doesn't match the columns headers; on and on.
CSV is a format defined by RFC with a variety of dialects in active use, particularly that of Microsoft Excel. It is not parseable correctly with simple methods like Apex's String#split()
. A CSV parser must correctly handle cells with embedded commas, rows with embedded newlines, and quoted cells, including internal escaped quotes.
Apex is not well suited to parsing CSV at all, still less parsing it in a way that is both performant and respectful of governor limits. Even if you write the world's best Apex CSV parser, you're still limited to operating on strings of up to 6 million characters (or you get a StringException
), or a maximum of 12 megabytes of heap covering both your file and your data (if and only if you are in an asynchronous context).
In the vast majority of implementation contexts, one of the other possible architectures is better in every way:
- Parse a CSV uploaded by a user in a Lightning component on the front end, using an existing, specialized CSV library like PapaParse. Pass data from the CSV into Apex to be persisted in the database. Write your validation logic in either JavaScript or Apex.
- Use an actual enterprise middleware or ETL platform that can parse CSV data and manage the integration of the data into Salesforce for you without heap limitations.
In the future, Evergreen functions may be another option.
But adopting Apex is likely to hamstring you and produce significant limitation and unreliability in your implementation.