How to create or generate a csv file in Apex Salesforce

by Rijwan Mohmmed
0 comment

Hello Friends, today we will learn How to create or generate a csv file in apex code Salesforce and send this to email as attachments. Many times we need to send data files in email via apex code and csv files are the best things that we can easily show the data by column header.

Also check this: Reusable Datatable in Lightning Web Component(LWC) Salesforce

Code :

The below code will query all Account object records and send CSV files to email. In code I have put my email id you can replace it with your email Id.

CreateCSVFIleTechdicerCtrl.cls :

public class CreateCSVFIleTechdicerCtrl {

    public static void createCsv(){
        String csvColumnHeader;
        List<String> csvRowValues = new List<String>();
        String parentId;
        for(Account acc : [SELECT Id, Name, Type, AccountNumber, CreatedDate FROM Account LIMIT 10]){
            String formattedDate = acc.CreatedDate.format('M/d/yyyy h:mm:ss a z');
            String accountName = acc.Name != null ? String.valueOf(acc.Name).escapeCsv() : '';
            String accountType = acc.Type != null ? acc.Type : '';
            String accountNumber = acc.AccountNumber != null ? acc.AccountNumber : '';
            String csvRowVal = formattedDate + ',' + accountName + ',' + accountType + ',' + accountNumber;
            parentId = acc.Id;
            csvColumnHeader = 'Date, Name, Type, Account Number\n';
            String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');

            //send email
            Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            Messaging.EmailFileAttachment attach1 = new Messaging.EmailFileAttachment();
            blob b;
            if(Test.isRunningTest()) { 
                b = blob.valueOf('Unit.Test');
            } else {
                b = Blob.valueOf(csvFile);

            message.setFileAttachments(new Messaging.EmailFileAttachment[]{attach1});
            String[] toAddresses = new String[] {''}; 
            message.setHtmlBody('This email is for testing purpose of Create csv files');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { message });


Reference :

  1. Salesforce

You may also like

Leave a Comment