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
Attribution to: PepeFloyd
Possible Suggestion/Solution #1
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.
Attribution to: Phil Hawthorn
Possible Suggestion/Solution #2
Just tried this quickly, and replacing \r\n with space seems to get rid of the newline. You might want to replace with stops.
System.debug([Select Id, Description from Case].Description.replaceAll('\r\n',' '));
Attribution to: techtrekker
Possible Suggestion/Solution #3
Generally when working with CSVs, you can delimit columns with quotation marks or some other character for this; the delimiting character is then escaped in the data.
An example would be "Column\nA", "Column ""B"""
Most programs, including Excel, will honor this when opening the CSV.
Attribution to: Mike Chale
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/3457