+ Start a Discussion
ranga babu vangalapudi 2ranga babu vangalapudi 2 

export data in the form of excel using batch apex

Hi,
when Iam trying to export data in the form of excel using batch apex and sent a mail attachement.
iam able to extract it in the form of excel but issue is when iam sending an email attachement it is going as an html, after opening that html only i can able to open the excel
 attaching the mail notification for your reference
Mail Notification what i am getting
following is the code:
global class AccountBatchExport implements Database.Batchable<sObject>,Database.Stateful {
       global final String query='Select Id,Name,AccountNumber,Type,Active__c from Account where CreatedDate<Today';   
    Public String generatedCSVFile ='';
    Public string[] Lines;
    global Database.QueryLocator start(Database.BatchableContext BC){
        lines = new String[0];
      return Database.getQueryLocator(query);        
   }
   global void execute(Database.BatchableContext BC,List<Account> scope){
           for(Account a: scope){            
        string fileRow = '';
        fileRow = fileRow +'\t'+ a.Id;
            fileRow = fileRow +'\t'+ a.Name;
        fileRow = fileRow +'\t'+ a.AccountNumber;
            fileRow = fileRow +'\t'+ a.Type;
        fileRow = fileRow +'\t'+ a.Active__c;
        fileRow = fileRow.replaceFirst('\t','');
            lines.add(fileRow);
        }        
   }
   global void finish(Database.BatchableContext BC){
        generatedCSVFile = generatedCSVFile + string.join(lines, '\n');
           lines=null;
           String today = Datetime.now().format('dd-MM-yyyy');
        Blob csvBlob = blob.valueOf(generatedCSVFile);
        String csvName = 'Accounts Data as on '+today+'.xls';
           Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
        csvAttachment.setFileName(csvName);
        csvAttachment.setBody(csvBlob);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'myemail@gmail.com'};
        String subject = 'Accounts Data as on '+today+'';
        email.setSubject(subject);
        email.setToAddresses(toAddresses);
        email.setPlainTextBody('Accounts Data as on '+today+'');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
        Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});       
   }
}

Thanks & Regards,
Ranga