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
Urich NOUPIKUrich NOUPIK 

Export record in multi columns CSV file

Hi, i want to export my record data in multi columns csv file (each columns per fields).
Now, i just export it in single column (field separated by comma) after clic on lightning button.
Someone can help me please. 
Below are the codes.

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

project1Home.cmp
<aura:component controller="GenerateCSV" implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" >
    <aura:attribute name="ObPerLst" type="ObjectPermissions[]"></aura:attribute>
    <!--aura init handler , call js "loadAcctRcrds" function that use  "GenerateCSV" controller and load "ObPerLst" object-->   
    <aura:handler name="init" value="{!this}" action="{!c.loadAcctRcrds}"/>
    <!-- NEW FORM -->
    <lightning:layout>
        <lightning:layoutItem padding="around-small" size="6">
            <!-- Header -->
            <c:project1Header/>
            <!-- / Header -->
            <div aria-labelledby="ClicDiv">
                <!-- BOXED AREA -->
                <fieldset class="slds-box slds-theme--default slds-container--small">
                    <legend id="newMetadata" class="slds-text-heading--small 
                                                       slds-p-vertical--medium">
                        Generate profile's metadata
                    </legend>
                    
                    <!-- CREATE FORM -->
                    <form class="slds-form--stacked">
                        <!--<ui:inputText aura:id="n1" maxlength="5" size="5" label="Number1" required="true"/>
                        <ui:inputText aura:id="n2" maxlength="5" size="5" label="Number2" required="true"/>-->
                        <lightning:button label="Generate" 
                                          class="slds-m-top--medium"
                                          variant="brand"
                                          onclick="{!c.ClickExport }"  />
                    </form>
                    <!-- / CREATE FORM -->
                    {!v.body}
                </fieldset>
                <!-- / BOXED AREA -->
            </div>
        </lightning:layoutItem>
    </lightning:layout>
    <!-- / NEW FORM -->
</aura:component>

project1HomeController.js
({
    loadAcctRcrds:function(component,event,helper){
       var action = component.get("c.getObjectPermissions");
        action.setCallback(this,function(response){
        var state = response.getState();
            if(state == "SUCCESS"){
                component.set("v.ObPerLst",response.getReturnValue());
            }
            else{
                alert('failed');
            }
        });
        $A.enqueueAction(action);     
    },
    // ClickExport take component object "ObPerLst" load by init handler and convert it to csv file using helper method
    ClickExport : function(component, event, helper) {
         var stockData = component.get("v.ObPerLst") 
         var csv = helper.convertArrayOfObjectsToCSV(component,stockData);
          if (csv == null){return;} 

        // ####--code for create a temp. <a> html tag [link tag] for download the CSV file--####     
         var hiddenElement = document.createElement('a');
          hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
          hiddenElement.target = '_self'; // 
          hiddenElement.download = 'ExportData.csv';  // CSV file Name* [.csv extension is obligatory] 
          document.body.appendChild(hiddenElement); // Required for FireFox browser
          hiddenElement.click(); // using click() js function to download csv file
    }
   
})

project1HomeHelper.jsp
({
    convertArrayOfObjectsToCSV : function(component,objectRecords){
        // declare variables
        var csvStringResult, counter, keys, columnDivider, lineDivider,parentKey;
        // check if "objectRecords" parameter is null, then return from function
        if (objectRecords == null || !objectRecords.length) {
            return null;
         } 
        // store ,[comma] in columnDivider variable for sparate CSV values and 
        // for start next line use '\n' [new line] in lineDivider variable  
        columnDivider = ',';
        lineDivider =  '\n';

        // in the keys valirable store fields API Names as a key 
        // this labels use in CSV file header
        keys = ['Id','Parent','Parent','SobjectType','PermissionsCreate', 'PermissionsRead', 'PermissionsEdit', 'PermissionsDelete', 'PermissionsModifyAllRecords', 'PermissionsViewAllRecords' ];
        
        parentKey=['Id'];//parentKey=['AccountNumber'];

        csvStringResult = '';
        csvStringResult += keys.join(columnDivider);/* space header information here*/
        csvStringResult += lineDivider;

        for(var i=0; i < objectRecords.length; i++){   
            counter = 0;

             for(var sTempkey in keys) {
                 var skey = keys[sTempkey] ;
                 
                 // add , [comma] after every String value,. [except first]
                 if(counter > 0){
                     csvStringResult += columnDivider;
                 }
                 //csvStringResult += '"'+ objectRecords[i][skey]+'"';
                 if(typeof objectRecords[i][skey] === 'object'){
                     csvStringResult += '"'+ objectRecords[i][skey].Name+'"';
                 }else{
                     csvStringResult += '"'+ objectRecords[i][skey]+'"';
                 }
                
               counter++;

             } // inner for loop close     
             csvStringResult += lineDivider;
          }// outer main for loop close 

       // return the CSV formate String 
        return csvStringResult;        
    },
})

project1Header.cmp
<aura:component >
    <!-- PAGE HEADER -->
    <lightning:layout class="slds-page-header slds-page-header--object-home">
        <lightning:layoutItem>
            <lightning:icon iconName="action:goal" alternativeText="Generate metadata"/>
        </lightning:layoutItem>
        <lightning:layoutItem padding="horizontal-small">
            <div class="page-section page-header">
                <h1 class="slds-text-heading--label">Get out metadata</h1>
                <h2 class="slds-text-heading--medium">Get out my metadata</h2>
            </div>
        </lightning:layoutItem>
    </lightning:layout>
    <!-- / PAGE HEADER -->
</aura:component>

GenerateCSV.apxc
public Class GenerateCSV {
    @AuraEnabled
    public static List<ObjectPermissions> getObjectPermissions() {
        return [SELECT Id, Parent.Name, Parent.Profile.Name, SobjectType, PermissionsCreate, PermissionsRead, 
                PermissionsEdit, PermissionsDelete, PermissionsModifyAllRecords, PermissionsViewAllRecords 
                FROM ObjectPermissions
                ORDER BY Parent.Name, SObjectType];
                //ORDER BY Parent.Profile.Name, SObjectType];
    }
}
Urich NOUPIKUrich NOUPIK
I find out my problem. 
1. i changed the extension of excel file (using XLS instead of CSV)
2. change the column delimiter ("\t" instead of "," )