Tuesday, 11 October 2016

How to create or generate a csv file in apex code Salesforce (Generate Setup Audit Trail records as CSV file)

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,

  1. 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

  1. global class SetupAuditTrailBatch implements Database.Batchable<sObject>, Database.Stateful {
  2.    
  3.     global String csvColumnHeader;
  4.     global List<String> csvRowValues = new List<String>();
  5.    
  6.     global Database.QueryLocator start(Database.BatchableContext BC){
  7.         //Query all SetupAuditTrail records.
  8.         String query = 'SELECT CreatedDate, CreatedBy.Username, Display, Section, Action, DelegateUser, CreatedById, CreatedBy.Name FROM SetupAuditTrail ORDER BY CreatedDate DESC';
  9.         return Database.getQueryLocator(query);
  10.     }
  11.    
  12.     global void execute(Database.BatchableContext BC, List<sObject> scope){
  13.         //Process retrieved SetupAuditTrail records and format field values.
  14.         for(SetupAuditTrail currSetupAudit : (List<SetupAuditTrail>) scope){
  15.             String formattedDate = currSetupAudit.CreatedDate.format('M/d/yyyy h:mm:ss a z');
  16.             String userName = currSetupAudit.CreatedBy.Username != null ? currSetupAudit.CreatedBy.Username : '';
  17.             String displayVal = currSetupAudit.Display != null ? String.valueOf(currSetupAudit.Display).escapeCsv() : '';
  18.             String sectionVal = currSetupAudit.Section != null ? currSetupAudit.Section : '';
  19.             String delegateUser = currSetupAudit.DelegateUser != null ? currSetupAudit.DelegateUser : '';
  20.            
  21.             String rowStr = formattedDate + ',' + userName + ',' + displayVal + ',' + sectionVal + ','+ delegateUser;
  22.             csvRowValues.add(rowStr);
  23.         }
  24.     }
  25.    
  26.     global void finish(Database.BatchableContext BC){
  27.         List<Folder> folders = [SELECT Id, Name FROM Folder WHERE Name = 'Setup Audit Trail Logs'];
  28.        
  29.         if(!folders.isEmpty()){
  30.             String documentName = 'SetupAuditTrailLog-'+ Datetime.now().format('MMM') + Datetime.now().year();
  31.             csvColumnHeader = 'Date, User, Action, Section, Delegate User\n';
  32.             String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');
  33.            
  34.             // Insert the generated CSV file in Document object under "Setup Audit Trail Logs".
  35.             Document doc = new Document(Name = documentName, Body = Blob.valueOf(csvFile), FolderId = folders[0].Id, Type = 'csv', ContentType='application/vnd.ms-excel');
  36.             insert doc;
  37.         }
  38.     }
  39. }


References:


Supported calls:
query(), retrieve()

Note:
Aggregate queries aren’t supported on this object. For example, SELECT count() FROM SetupAuditTrail works but SELECT count(Id) FROM SetupAuditTrail fails.

16 comments:

  1. very informative blog and useful article thank you for sharing with us , keep posting learn more aboutsalesforce training,salesforce online training

    ReplyDelete
  2. HI,I implemented this logic to create a csv file based on LastModifiedDate.It did generate the file correctly with all values.Today when I ran the batch it is creating a csv bt does not have any values.I queried and there are 3 records based on the soql.I am posting my code below,any help is highly appreciated since I need to get it up and running soon.
    global class BatchGenerateUpdatedMeterFile implements Database.Batchable, Database.Stateful
    {
    global String csvColumnHeader;
    global List csvRowValues = new List();

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
    //Query all modified meter records

    Date dt = date.today();
    System.debug(dt);
    String query = 'SELECT Id,Name,parcel__r.Name, Module_Number__c,Meter_Install_Date__c from sm1e__smEquipment__c WHERE LastModifiedDate = Today';
    return Database.getQueryLocator(query);

    }


    global void execute(Database.BatchableContext BC ,List scope)
    {
    //Process retrieved records and format field values.
    for(sm1e__smEquipment__c currentList : (List) scope){

    String parcelName = currentList.parcel__r.Name;
    System.debug(parcelName);
    String moduleNumber = currentList.Module_Number__c;
    Date meterInstallDate = currentList.Meter_Install_Date__c;
    String meternumber = currentList.Name;


    String rowStr = meternumber + ',' + parcelName + ',' + moduleNumber ;
    csvRowValues.add(rowStr);

    }


    }

    global void finish(Database.BatchableContext BC)
    {
    List folders = [SELECT Id, Name FROM Folder WHERE Name = 'BeaconExportFolder'];

    if(!folders.isEmpty()){
    String documentName = 'MeterDataExportFile-'+Datetime.now().format('dd/MM/yyyy');
    csvColumnHeader = 'MeterNumber , Address ,ModuleNumber ,InstallDate \n';
    String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');

    //Insert the genertaed CSV file in Document object under 'BeaconExportFolder'

    Document doc = new Document(Name = documentName, Body = Blob.valueOf(csvFile),FolderId = folders[0].id,
    Type = 'csv', ContentType ='application/vnd.ms-excel');
    insert doc;
    System.debug('File inserted');
    }


    }
    }

    ReplyDelete
  3. I figured it out.The batch apex was taking time to complete.

    ReplyDelete
  4. Very good points you wrote here..Great stuff...I think you've made some truly interesting points.Keep up the good work. Free TikTok Fans

    ReplyDelete
  5. Thanks for sharing this great information on Oracle APEX. Actually I was looking for the same information on internet for Oracle Apex Interview Questions and Answers and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject, you can learn more about Oracle PPM Cloud by attending Oracle APEX Training.

    ReplyDelete
  6. This was exactly what I needed. The Database.Stateful in the class header is a must. If it is not there, csvRowValues loses scope in the finish routine and will be blank. Only took me 1 hour to find that missing piece in my code. Thanks again for posting this.

    ReplyDelete
  7. I was looking for similar type of example, its a very good once. Thanks a lot.

    ReplyDelete
  8. Salesforce Service Cloud is about ensuring that businesses provide exceptional customer service. It's like having a virtual customer care team on hand 24 hours a day, seven days a week. Salesforce Service Cloud Implementation can be a challenging yet rewarding experience, but it is important to streamline their customer service operations, improve their agent productivity, and ultimately enhance their overall customer experience.

    With Salesforce Service Cloud Implementation, you can easily assist your businesses to leverage the power of Salesforce to achieve your business goals. Request a free consultation with an AblyPro expert to learn how Salesforce Service Cloud may help your company improve customer service and drive higher retention rates!

    ReplyDelete
  9. Great tutorial! Generating CSV files in Apex code in Salesforce is a practical way to extract Setup Audit Trail records for reporting or compliance purposes. This method can also be very useful when you need to migrate data from Salesforce to Zoho CRM efficiently. Clear examples like these make it much easier for developers to implement.

    ReplyDelete
  10. A python language course builds strong programming fundamentals with structured guidance. It explains syntax, loops, and data structures clearly. This python language course focuses on practical coding exercises. It enhances logical thinking and debugging skills. Learners gain real-time implementation knowledge. It is reliable and career-oriented.

    ReplyDelete
  11. MuleSoft Classes provide hands-on training for developers and IT professionals who want to learn API development and system integration. These classes cover Mule 4 fundamentals, DataWeave transformations, API design, and deployment strategies. With expert instructors and real-time projects, MuleSoft classes help learners build practical integration skills and prepare for MuleSoft certification exams.mulesoft classes

    ReplyDelete
  12. Tableau online training offers detailed knowledge of business intelligence tools and visualization techniques. It explains data connections and dashboard publishing clearly. This tableau online training improves analytical thinking and reporting accuracy. Learners gain real-time project experience. Practical labs are included. Certification guidance is provided. It prepares industry-ready professionals.

    ReplyDelete
  13. I really like how the Ab Initio course content includes practical topics like data transformation, joins, sorting, and workflow execution.
    ab initio course contentThese skills are crucial for building real-world ETL pipelines and managing enterprise data systems.

    ReplyDelete
  14. A well-structured Mule software training program helps developers understand enterprise integrations, API design, and data transformations in a practical way.mule software training

    ReplyDelete
  15. Thanks for the guide! Getting a Mule Soft certification definitely looks like a great way to boost career opportunities.mule soft certification

    ReplyDelete

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...