[SalesForce] Encode Long Text Area field

I am working on some code that retrieves certain cases and then emails those cases as a csv. This is working to some extent. The problem I have is that one of the fields is 'Description' which is a long text area field, this means the values here can contain newlines and special characters.

When a case has a description with at least 1 newline, it breaks the formatting of the csv file I receive as it converts those extra lines in the description into new rows in the csv file.

You can see commented in the code below what I've done to solve this but I am not sure this is the correct way to do it. At this point, I am getting the value in a single column but now I have many html encoded characters in that column in the CSV.

Code that generates rows/files:

string header = 'Record Id, Case Number , Created Date, Modified Date, subject, description, Web Name, Web Email, \n';
            string finalstr = header ;

               for(Case c: junklist)

                {
                  string description=encodingutil.urlencode(c.description,'UTF-8').replace('+',' '); // Doing this has somehow solved the problem. 

                  string recordString = c.id+','+c.casenumber+','+c.CreatedDate+','+c.LastModifiedDate +','+ c.subject+','+ description 
                  +','+c.suppliedname+','+c.suppliedemail+ '\n';
                  finalstr = finalstr +recordString;
                }

Thanks

Best Answer

Can you not simply use String.replace to replace the new line character (\n) with e.g. a space:

String description = c.description.replace('\n', ' ');

Also, if some of the other special characters include " and , etc. that will mess up your csv it would be worth doing some kind of replace/escape on those too.

Related Topic