0

I have a CSV file uploaded in Salesforce Document, That CSV contains line breaks within the cell. So when I try to parse this CSV file with "csvFileContent.split('\n')", I am expecting all rows of CSV should have been split to Array of String, but this Split function is considering the line breaks within the cell also a new line hence I am unable to parse the CSV file properly.

Below is the snapshot of my CSV file and Apex code I am using to read this CSV file. Please help me with splitting CSV file rows properly without breaking the CSV cell.

Snapshot of CSV file contents:

enter image description here

I am trying to parse above CSV file using below code:

List<Document> docList = [SELECT Id, Body FROM Document WHERE Folder.developerName = 'Article_Migration' AND DeveloperName = 'Articles_csv'];
if(docList != null && docList.size() > 0){
Blob csvFile = docList[0].Body;
if(csvFile != null){
    String csvFileContent = csvFile.toString();
    List<String> fileRows = new List<String>();
    List<String> rowCells = new List<String>(); 
    fileRows = csvFileContent.split('\n'); //I have 4 rows in CSV file, it should have split the csv file into 4 rows but fileRows list have more than 4 rows
    if(fileRows.size() > 0){
        for(Integer countFor=1 ; countFor < fileRows.size() ; countFor++){
            rowCells = fileRows[countFor].split(',');
            //some logic to read the CSV file
        }
    }
}
}
2
  • Are the cell contents wrapped in quotation marks (")? Commented Oct 20, 2022 at 19:26
  • I just got a chance to circle back to this, I'll just say this: CSV parsing is not just "splitting lines". There's a fair bit of work that goes into it. I've linked a stateful parser that I wrote up, you can find others, too, depending on your specific needs. My parser returns a List<Map<String, String>> which organizes the data nicely, but is slower than other implementations. It links to one from Daniel Ballinger that's also decently powerful. Commented Oct 20, 2022 at 20:43

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.