function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Robin BarnwellRobin Barnwell 

Scheduling a VisualForce page export

I've created a VisualForce page that creates a CSV file from an Apex query, code below. 

I now want to run this once per hour to export the data to another system.  I plan to use the Apex scheduler for this, so no problem there.

The bit I'm stuck on is the Apex code that will invoke the Visualforce page to create the file.  Anyone done this before please?

VF
<apex:page controller="CSV_create" action="{!say_hello}" contentType="text/csv#{!now() }">
  <apex:repeat value="{!lstAcc}" var="x">
      {!x.id},{!x.name}
  </apex:repeat>
</apex:page>

APEX
public class CSV_create
{    
    public string header{get;set;}
    public List<TheAcc> lstAcc {get; set;}
    public class TheAcc {
        public string id {get; set;}
        public string name {get; set;}       
    }


    public CSV_create(){
            lstAcc = new List<TheAcc>();
    }

    Public void say_hello()
    {
       string queryString = 'select id, name from account';
       List<Account> lstAccs = DataBase.Query(queryString);       
       if(lstAccs.size()>0){
              for(Account Acc :lstAccs){
                  TheAcc a = new TheAcc();
                  a.id = Acc.id;
                  a.name = Acc.name + '\r\n';                  
                  lstAcc.add(a);               
              } 
        } 
    }
}
Robin BarnwellRobin Barnwell
Just to add.  I've tried accessing the URL direct thinking it might generate the CSV, but no luck.  This runs but doesn't cuase the VF page to create the CSV. But going direct to the URL in Chrome does work

    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://cs89.salesforce.com/apex/CSV_create');
    req.setMethod('POST');
    HttpResponse res = h.send(req);
    system.debug('Details ' + res.getStatus());
Robin BarnwellRobin Barnwell
It's OK, I've cracked it.  Now have PoC of downloadable CSV files running in batch for FTP transfer.