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
sfadm sfadmsfadm sfadm 

Generate csv report via apex

Hello,

Please advise how to generate a .csv file report via apex?

What I would like to achieve is to automatically generate a .csv report file in the beginning and at the end of a working week.

Please advise how this can be achieved with an apex code?

I'll strongly appreciate if you can include an apex source code example.
NagendraNagendra (Salesforce Developers) 
Hi,

Here is the sample code to create or generate a CSV file using apex code. The below code will query all SetupAuditTrail object records and stored the generated CSV file in document object folder. 

Usually Setup Audit Log in salesforce will provide only last six month of data. But when we need a specific range of logs, then we have to go for a custom logic. 

The below query will provide specific date range of Audit logs,
SELECT CreatedDate, CreatedBy.Username, Display, Section, Action, DelegateUser FROM SetupAuditTrail WHERE CreatedDate >= 2016-09-10T00:00:00Z AND CreatedDate <= 2016-10-01T00:00:00Z ORDER BY CreatedDate DESC
Sample Batch Code:
global class SetupAuditTrailBatch implements Database.Batchable<sObject>, Database.Stateful {
   
    global String csvColumnHeader;
    global List<String> csvRowValues = new List<String>();
   
    global Database.QueryLocator start(Database.BatchableContext BC){
        //Query all SetupAuditTrail records.
        String query = 'SELECT CreatedDate, CreatedBy.Username, Display, Section, Action, DelegateUser, CreatedById, CreatedBy.Name FROM SetupAuditTrail ORDER BY CreatedDate DESC';
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        //Process retrieved SetupAuditTrail records and format field values.
        for(SetupAuditTrail currSetupAudit : (List<SetupAuditTrail>) scope){
            String formattedDate = currSetupAudit.CreatedDate.format('M/d/yyyy h:mm:ss a z');
            String userName = currSetupAudit.CreatedBy.Username != null ? currSetupAudit.CreatedBy.Username : '';
            String displayVal = currSetupAudit.Display != null ? String.valueOf(currSetupAudit.Display).escapeCsv() : '';
            String sectionVal = currSetupAudit.Section != null ? currSetupAudit.Section : '';
            String delegateUser = currSetupAudit.DelegateUser != null ? currSetupAudit.DelegateUser : '';
           
            String rowStr = formattedDate + ',' + userName + ',' + displayVal + ',' + sectionVal + ','+ delegateUser;
            csvRowValues.add(rowStr);
        }
    }
   
    global void finish(Database.BatchableContext BC){
        List<Folder> folders = [SELECT Id, Name FROM Folder WHERE Name = 'Setup Audit Trail Logs'];
       
        if(!folders.isEmpty()){
            String documentName = 'SetupAuditTrailLog-'+ Datetime.now().format('MMM') + Datetime.now().year();
            csvColumnHeader = 'Date, User, Action, Section, Delegate User\n';
            String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');
           
            // Insert the generated CSV file in Document object under "Setup Audit Trail Logs".
            Document doc = new Document(Name = documentName, Body = Blob.valueOf(csvFile), FolderId = folders[0].Id, Type = 'csv', ContentType='application/vnd.ms-excel');
            insert doc;
        }
    }
}
Hope this helps.

Kindly mark this as solved if the reply was helpful.

Thanks,
Nagendra

 
Ameer Basha 34Ameer Basha 34
HI Nagendra,

I have tried your code snippet but i am not able to fetch record data in excel sheet, as i have made some changes to pull account object record.
Please kindly help me to get records in excel sheet. 

Thank you,
Ameer