CSV File Download from Lightning Component

Use below code to download data as a  CSV file from the lightning component.

Component 

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global">
    <!-- 1.attribute to store return value and show on component. -->
    <aura:attribute name="gridData" type="Object"/>
    <!-- 2.handler to call method "doInit" of jsCOntroller on loading of component. -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> 
    <div class="slds-m-around--xx-large">     
        <button class="slds-button slds-button--brand" onclick="{!c.downloadCSV}">Download As CSV</button> <br/><br/>
        <table class="slds-table slds-table--bordered" id="pbId">
            <!-- 3.Header of table. -->
            <thead>
                <tr class="slds-text-heading--label">            	
                    <aura:iteration items="{!v.gridData.headers}" var="col">                             
                        <th class="{!col.cssClass}"> {!col.title} </th>
                    </aura:iteration>             
                </tr>        	
            </thead>
            <!-- 4.Body of table. -->
            <tbody>
                <!-- Limitation - we cannot use indexvar of iterator control to refer header json information else, instead of defining css class for each column, we could have used it from header only -->
                <aura:iteration items="{!v.gridData.rows}" var="row">
                    <tr class="slds-hint-parent">
                        <aura:iteration items="{!row.vals}" var="col" indexVar="idx">                       
                            <td id="{!'theTd__' + idx}" class="{!col.cssClass}">{!col.val}</td>
                        </aura:iteration>
                    </tr>
                </aura:iteration>           
            </tbody>   
        </table>
    </div>
</aura:component>

Controller.js

({
    doInit : function(component, event, helper) {
        // 1. Calling helper method "doInit".
        helper.doInit(component, event, helper);
    },
    // 2. Method to download CSV file.
    downloadCSV : function(component, event, helper,fileTitle) {
        // 3. Getting table data to download it in CSV.
        var gridData = component.get("v.gridData");
        // 4. Spliting headers form table.
        var gridDataHeaders = gridData["headers"];
        // 5. Spliting row form table.
        var gridDataRows = gridData["rows"];
        // 6. CSV download.
        var csv = '';
        for(var i = 0; i < gridDataHeaders.length; i++){         
            csv += (i === (gridDataHeaders.length - 1)) ? gridDataHeaders[i]["title"] : gridDataHeaders[i]["title"] + ','; 
        }
        csv += "\n";
        var data = [];
        for(var i = 0; i < gridDataRows.length; i++){
            var gridRowIns = gridDataRows[i];
            var gridRowInsVals = gridRowIns["vals"];
            var tempRow = [];
            for(var j = 0; j < gridRowInsVals.length; j++){                                     
                var tempValue = gridRowInsVals[j]["val"];
                if(tempValue.includes(',')){
                    tempValue = "\"" + tempValue + "\"";
                }
                tempValue = tempValue.replace(/(\r\n|\n|\r)/gm,"");                 
                tempRow.push(tempValue);
            }
            data.push(tempRow); 
        }
        data.forEach(function(row){
            csv += row.join(',');
            csv += "\n";
        });
        // 6. To download table in CSV format.
        var hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
        hiddenElement.target = '_blank';
        hiddenElement.download = 'fileTitle'+'.csv'; 
        hiddenElement.click();
    }
    
})

helper.js

({
    
    doInit : function(component, event, helper) {
        // 1. Calling method "getSampleJSON()" and parsing it into JSON object.
        var jsonData = JSON.parse(helper.getSampleJSON());
        // 2. Setting parsed data in attribute "gridData".
        component.set("v.gridData",jsonData);
    },
    getSampleJSON : function(){
        // 3. Variable declaration and assigning value to show in component.
        var jsonStr = '{"rows":[{"vals":[{"val":"Salesforce","cssClass":""},{"val":"SFO","cssClass":""},{"val":"info@Salesforce.com","cssClass":""},{"val":"8602229632","cssClass":"responsiveHide"}]},{"vals":[{"val":"Microsoft","cssClass":""},{"val":"SFO","cssClass":""},{"val":"info@microsoft.com","cssClass":""},{"val":"8602283222","cssClass":"responsiveHide"}]},{"vals":[{"val":"SAP","cssClass":""},{"val":"SFO","cssClass":""},{"val":"info@SAP.com","cssClass":""},{"val":"8600942222","cssClass":"responsiveHide"}]},{"vals":[{"val":"Google","cssClass":""},{"val":"SFO","cssClass":""},{"val":"info@Google.com","cssClass":""},{"val":"8602479222","cssClass":"responsiveHide"}]}],"headers":[{"title":"ClientName","isSortable":false,"dataType":"","cssClass":""},{"title":"Address","isSortable":false,"dataType":"","cssClass":""},{"title":"Email","isSortable":false,"dataType":"","cssClass":""},{"title":"Mobile","isSortable":false,"dataType":"","cssClass":"responsiveHide"}]}';
        return jsonStr;
    }           
})

Sample App for testing

<aura:application extends="force:slds">
    <c:DownloadAsCsv/>
</aura:application>