Rendering a Visualforce page as CSV

In this article we will learn how to render a visualforce page as CSV in Salesforce.

In order to render a visualforce page as CSV you have to set contentType attribute to text/csv.

Have a look at below code example where I have created a Visualforce page which is rendered as CSV. CSV will display the list of 5 accounts fetched using Apex.

<apex:page controller="CSVExportController" contentType="text/csv">
    <apex:outputText value="{!CsvData}" escape="false"/>
</apex:page>

Below is the Apex Controller Named CSVExportController which will fetch 5 account records from Salesforce. After fetching the records from Salesforce we are creating a String variable named csvContent which will hold all the CSV data.

I have also written method named formatField which will handle null values and escape quotes.

public class CSVExportController {
    public String getCsvData() {
        // Fetch the data
        List<Account> accounts = [SELECT Name, Industry, Type FROM Account LIMIT 5];
        
        // Build the CSV content
        String csvContent ='Name,Industry,Type'+'\n';
        for (Account acc : accounts) {
            csvContent = csvContent+''+(formatField(acc.Name) + ',' + 
                              formatField(acc.Industry) + ',' + 
                              formatField(acc.Type) + '\n');
        }
        return csvContent.toString();
    }
    
    // Helper method to handle null values and escape quotes
    private String formatField(String field) {
        if (field == null) return ''; // Handle null
        field = field.replace('"', '""'); // Escape double quotes for CSV
        return '"' + field + '"'; // Wrap in quotes
    }
}

Also, check out the below video on How to Render Visualforce Page as CSV in Salesforce?

I hope you find this article helpful. Let us know which topic we should cover next.

Leave a Comment