Hello friends, In this post we will learn, how to create/generate a csv file using apex code and send this to email attachment. CSV files are the best things that we can easily show the data by column header. So let's get started,

Create/Generate csv file using apex

In this example I had used a custom object to query data and then convert those lists of data in the csv file. You can use any of the object as per you need. So the sample code are:

Code Example:
 public class CSVGenerateHandler {    
    
    public static void generateCSV(){
        String csvColumnHeader='RecordId,ObjectName,RecordName\n';
        List<String> csvRowValues = new List<String>();
        List<RecordObject__c> lstRec=[SELECT Record_Id__c,Object_Name__c,Record_Name__c FROM RecordObject__c limit 10];
        for(RecordObject__c rec :lstRec){
            String RecordId = rec.Record_Id__c != null ? rec.Record_Id__c : '';
            String ObjectName = rec.Object_Name__c != null ? rec.Object_Name__c.escapeCsv() : '';
            String RecordName = rec.Record_Name__c != null ? rec.Record_Name__c.escapeCsv() : '';
            String csvRowVal = RecordId + ',' + ObjectName + ',' + RecordName;
            csvRowValues.add(csvRowVal);            
        }
        String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');
        
        //send email with csv file
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
        blob b;
        if(!Test.isRunningTest()) { 
            b = Blob.valueOf(csvFile);
        }
        attach.setFileName('RecordData.csv');
        attach.setBody(b);
        message.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});       
        message.setToAddresses(new List<String>{'smanisheng@gmail.com'});//please replace your own emailid here 
        message.setSubject('CSV File Via Apex'); 
        message.setHtmlBody('This email is for testing purpose of Create/Generate csv file');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { message });
    }
 }
Output:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.