To generate CSV file through Apex is fairly simple. Following steps will help you to understand it.
- Create a Controller and write a method which returns List of items.
public class generateCSVController{ public List LeadList{get;set;} public generateCSVController(){ //Populate List here. LeadList = [select id,name,email from lead limit 10]; } }
- Create a page and associate it with the controller we created in first step. Set the content type of the page to “text/csv”.
< apex:page controller="generateCSVController" cache="true" contentType="text/csv#Leads.csv" language="en-US" >"Id","Names","Email" < apex:repeat value="{!LeadList}" var="L" > "{!L.id}","{!L.name}","{!L.email}" < /apex:repeat > < /apex:page >