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
Ranjith MerguRanjith Mergu 

How to download list of records showing in the table as excel file and send email when we click on button using the aura components

Best Answer chosen by Ranjith Mergu
Priti jaiswal 8Priti jaiswal 8
H Ranjith,

Try this,

Server Side controller

public class SendOppDetails_Ctlr 
{
    @AuraEnabled
    public static void sendOppDetails(String attachmentBody, String attachmentName)
    {
        Id currentUserId = UserInfo.getUserId();
        User userDetail = [select id, Email from User where id =: currentUserId];
        
        String[] toAddress = new String[]{userDetail.Email};
        
        List<Messaging.Emailfileattachment> lstEfa = new List<Messaging.Emailfileattachment>();        
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        efa.setFileName(attachmentName);
        efa.setBody(blob.valueOf(attachmentBody));        
        lstEfa.add(efa);
        
        Messaging.SingleEmailMessage emailMesg = new Messaging.SingleEmailMessage();
        emailMesg.setToAddresses(toAddress);
        emailMesg.setPlainTextBody('Hello');
        emailMesg.setSubject('Opportuntiy Details');    
        emailMesg.setFileAttachments(lstEfa);            
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { emailMesg });
    }
    
    @AuraEnabled
    public static List<Opportunity> loadOppDetails()
    {
        return [Select id, Name, Account.Name from Opportunity Limit 20];
    }
}

Client side controller

({
    getOppDetails : function (component, event, helper)
    {
        var action1 = component.get("c.loadOppDetails");
        
        action1.setCallback(this, function(response)
        {
            if(component.isValid() && response.getState() == 'SUCCESS')
            {
                component.set("v.lstOpportunities", response.getReturnValue());
            }
        });
        $A.enqueueAction(action1);
    },
        
    sendEmailMesg : function(component, event, helper)
    {        
        var lstOfOpps = component.get("v.lstOpportunities");
        
        var data = [];
        var headerArray = [];
        var csvContentArray = [];
        var fileName = "Opportunities"
        var fielExtension = ".csv";  

        headerArray.push('Opportunity Name');
        headerArray.push('Account Name');
        data.push(headerArray);
        
        for(var i=0; i<lstOfOpps.length; i++)
        {
            var tempArray = [];
            tempArray.push(lstOfOpps[i].Name);
            tempArray.push(lstOfOpps[i].Account.Name);
            data.push(tempArray);
        }
            
        for(var j=0; j<data.length; j++)
        {
            var dataString = data[j].join(",");
            csvContentArray.push(dataString);
        }        
        
        var csvContent = csvContentArray.join("\n");        
        fileName =  fileName + fielExtension;
        
        var action = component.get("c.sendOppDetails");        
        action.setParams({"attachmentBody": csvContent, "attachmentName" : fileName});        
        action.setCallback(this, function(response)
        {
            var state = response.getState();
            alert(state);
            if(state == 'SUCCESS')
            {
                //do something
            }
        });
        $A.enqueueAction(action);
    }
})

Lightning Component

<aura:component controller = "SendOppDetails_Ctlr" implements="force:lightningQuickAction">

    <aura:handler name= "init" value="{!this}" action="{!c.getOppDetails}"/>    
    <aura:attribute name = "lstOpportunities" type = "Opportunity[]"/>
    
    <table>
        <tr>
            <th>Opportunity Name</th>
            <th></th>
            <th>Account Name </th>
        </tr>
    </table>
    
    <aura:iteration items = "{!v.lstOpportunities}" var = "opp">
        <table>
            <tr>
                <td style = "font-weight:bold;">{!opp.Name}</td>
                <td> </td>
                <td  style = "font-weight:bold;">{!opp.Account.Name}</td>
            </tr>
        </table>    
    </aura:iteration>
    <div>
        <lightning:button label="sendEmail" onclick="{!c.sendEmailMesg}"/>
    </div>
    <div>
    </div>
</aura:component>

Moodify the code according your requirement. Let me know it it works!!

Regards,
Priti

All Answers

Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Ranjith,

Download Data as CSV File With JavaScript In Salesforce Lightning Component.May I suggest you, please refer the below link for reference. Hope it will be helpful.

Best Regards
​Rahul Kumar
Priti jaiswal 8Priti jaiswal 8
H Ranjith,

Try this,

Server Side controller

public class SendOppDetails_Ctlr 
{
    @AuraEnabled
    public static void sendOppDetails(String attachmentBody, String attachmentName)
    {
        Id currentUserId = UserInfo.getUserId();
        User userDetail = [select id, Email from User where id =: currentUserId];
        
        String[] toAddress = new String[]{userDetail.Email};
        
        List<Messaging.Emailfileattachment> lstEfa = new List<Messaging.Emailfileattachment>();        
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        efa.setFileName(attachmentName);
        efa.setBody(blob.valueOf(attachmentBody));        
        lstEfa.add(efa);
        
        Messaging.SingleEmailMessage emailMesg = new Messaging.SingleEmailMessage();
        emailMesg.setToAddresses(toAddress);
        emailMesg.setPlainTextBody('Hello');
        emailMesg.setSubject('Opportuntiy Details');    
        emailMesg.setFileAttachments(lstEfa);            
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { emailMesg });
    }
    
    @AuraEnabled
    public static List<Opportunity> loadOppDetails()
    {
        return [Select id, Name, Account.Name from Opportunity Limit 20];
    }
}

Client side controller

({
    getOppDetails : function (component, event, helper)
    {
        var action1 = component.get("c.loadOppDetails");
        
        action1.setCallback(this, function(response)
        {
            if(component.isValid() && response.getState() == 'SUCCESS')
            {
                component.set("v.lstOpportunities", response.getReturnValue());
            }
        });
        $A.enqueueAction(action1);
    },
        
    sendEmailMesg : function(component, event, helper)
    {        
        var lstOfOpps = component.get("v.lstOpportunities");
        
        var data = [];
        var headerArray = [];
        var csvContentArray = [];
        var fileName = "Opportunities"
        var fielExtension = ".csv";  

        headerArray.push('Opportunity Name');
        headerArray.push('Account Name');
        data.push(headerArray);
        
        for(var i=0; i<lstOfOpps.length; i++)
        {
            var tempArray = [];
            tempArray.push(lstOfOpps[i].Name);
            tempArray.push(lstOfOpps[i].Account.Name);
            data.push(tempArray);
        }
            
        for(var j=0; j<data.length; j++)
        {
            var dataString = data[j].join(",");
            csvContentArray.push(dataString);
        }        
        
        var csvContent = csvContentArray.join("\n");        
        fileName =  fileName + fielExtension;
        
        var action = component.get("c.sendOppDetails");        
        action.setParams({"attachmentBody": csvContent, "attachmentName" : fileName});        
        action.setCallback(this, function(response)
        {
            var state = response.getState();
            alert(state);
            if(state == 'SUCCESS')
            {
                //do something
            }
        });
        $A.enqueueAction(action);
    }
})

Lightning Component

<aura:component controller = "SendOppDetails_Ctlr" implements="force:lightningQuickAction">

    <aura:handler name= "init" value="{!this}" action="{!c.getOppDetails}"/>    
    <aura:attribute name = "lstOpportunities" type = "Opportunity[]"/>
    
    <table>
        <tr>
            <th>Opportunity Name</th>
            <th></th>
            <th>Account Name </th>
        </tr>
    </table>
    
    <aura:iteration items = "{!v.lstOpportunities}" var = "opp">
        <table>
            <tr>
                <td style = "font-weight:bold;">{!opp.Name}</td>
                <td> </td>
                <td  style = "font-weight:bold;">{!opp.Account.Name}</td>
            </tr>
        </table>    
    </aura:iteration>
    <div>
        <lightning:button label="sendEmail" onclick="{!c.sendEmailMesg}"/>
    </div>
    <div>
    </div>
</aura:component>

Moodify the code according your requirement. Let me know it it works!!

Regards,
Priti
This was selected as the best answer
Ranjith MerguRanjith Mergu
Thank you very Much Priti,
 Its working well.

Thanks,
Ranjith