Generate CSV file in salesforce apex

I have faced an issue when I was generate CSV file from apex class. The issue is small but we need to take care of that if we are trying to get CSV file from salesforce code.

I have iterate the object list over the apex:repeat in VF page and put the values from that list. My previous code was:


public Class GenerateCSV {
    public List<Contact> getContacts() {
          return [select Id,Title,FirstName,LastName from Contact limit 20];
    }
}

This is my simple apex controller,fetch the contact record. And my VF page was looks as below:


<apex:page controller="GenerateCSV"  contentType="text/csv#Contact.csv" />"Title","First Name","Last Name"
    <apex:repeat value="{!Contacts}" var="con" >
         {!con.Title},{!con.FirstName},{!con.LastName}
    </apex:repeat>
</apex:page>

When I executed the page a CSV file is downloaded,so what is the error???? Actually the error contains in the downloaded CSV .

CSV abbreviation for “Comma Separated Value” , In which each value is separated with comma. So the output separate the values from comma. If a contact has title VP,technology the output is looks like:

CSV

In the above output the “VP,technology” is separated by comma and display in two different column due to this the last Name go the one column forward and the CSV file become incorrect.

To overcome this issue we need to put inverted commas outside the each values in VF page as


<apex:page controller="GenerateCSV" contentType="text/csv#Contact.csv" />"Title","First Name","Last Name"
     <apex:repeat value="{!Contacts}" var="con" >"{!con.Title}","{!con.FirstName}","{!con.LastName}"</apex:repeat>
</apex:page>

“{!con.Title}”,”{!con.FirstName}”,”{!con.LastName}” => All the value put inside the inverted commas so the VP,technology is taken as “VP,Technology” in CSV file.

CSV1

1 Comment

  1. Reddy

    Love you bro,
    This trick saved me 🙂 🙂 🙂

Leave a comment