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
KRITI LAHA 8KRITI LAHA 8 

generate csv file using apex

I have below code. I need to generate a csv file to show to results of 'userdetaillist'.

public class UserService {
    private static String profileName = 'Chatter Free User';
    private static String ps7Name = 'Test Chatter Free7';
   Public static List<UserDetail> userDetailList = new List<UserDetail>();
    
    
    private static List<String> ps1_ps10NameList = new List<String>{
        'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
    
    
    public static List<UserDetail> getUserPermissionDetails(){
        
      Map<Id, User> userMap = new Map<Id, User>([SELECT Id
                                  FROM User
                                  WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId 
                                                   FROM PermissionSetAssignment
                                                   WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
        //System.debug(usermap);
     Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
        
        for(PermissionSetAssignment psa : [SELECT AssigneeId, PermissionSet.label
                                              FROM PermissionSetAssignment
                                              WHERE AssigneeId = : userMap.keySet()
                                                  AND (PermissionSet.label IN :ps1_ps10NameList
                                                     OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
                                              ORDER BY AssigneeId, PermissionSet.label])
        {
            List<String> tempList = new List<String>();
               if(permissionSetMap.containsKey(psa.AssigneeId))
                tempList = permissionSetMap.get(psa.AssigneeId);
            
            tempList.add(psa.PermissionSet.label);
            
            permissionSetMap.put(psa.AssigneeId, tempList);
                    
        }

        return evaluateUser(permissionSetMap);
        
    }
    
    
    private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){

        Boolean additional;

        List<UserDetail> userDetailList = new List<UserDetail>();

        List<String> foundList = new List<String>();        
        for(Id id : permissionSetMap.keySet())
        {
            UserDetail ud = new UserDetail();
            additional = false;
            /*system.debug(permissionSetMap.get(id));*/
            foundList.clear();

            for(String str : permissionSetMap.get(id)){
            
                if(!ps1_ps10NameList.contains(str)){
                    additional = true;
                }else{
                    foundList.add(str);
                }
                /*system.debug(userDetailList);*/
            }            
            
            ud.Id = id;
            ud.permissionSetList = permissionSetMap.get(id);
            
            if(additional && ps1_ps10NameList.size() == foundList.size())
                ud.status = 'No Change And Additional';
            else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
                ud.status = 'Missing And Additional';
            else if(!additional && ps1_ps10NameList.size() != foundList.size())
                ud.status = 'Missing';
            else if(!additional && ps1_ps10NameList.size() == foundList.size())          
                ud.status = 'No Change';
                
            userDetailList.add(ud);
        }
        System.debug(JSON.serializePretty(userDetailList));
            return userDetailList;
       
       
    }
    
    public class UserDetail {
        
        public Id id;
        public List<String> permissionSetList;
        public String status;
    } 
   
}
 
Shri RajShri Raj

To generate a CSV file, you can use the CSVWriter class from the Apex Enterprise Patterns library. Here's an example of how to modify your code to generate a CSV file and write the results of userDetailList to it:
public class UserService {
    private static String profileName = 'Chatter Free User';
    private static String ps7Name = 'Test Chatter Free7';
    Public static List<UserDetail> userDetailList = new List<UserDetail>();
    
    // Add these two lines to import the necessary classes
    // Don't forget to add the Apex Enterprise Patterns library to your org first
    // See https://github.com/apex-enterprise-patterns/force-com-enterprise-patterns for more information
    import com.sforce.enterprise.patterns.CSVWriter;
    import com.sforce.enterprise.patterns.CSVWriter.CSVOptions;
    
    // ...

    public static void generateCSV() {
        // Call getUserPermissionDetails to populate userDetailList
        getUserPermissionDetails();
        
        // Create a new CSVWriter instance
        CSVWriter writer = new CSVWriter(new CSVOptions.Builder()
            .includeHeader(true)
            .build());
        
        // Define the headers for the CSV file
        String[] headers = new String[] {'Id', 'Permission Set List', 'Status'};
        
        // Write the headers to the CSV file
        writer.writeNext(headers);
        
        // Loop through userDetailList and write each UserDetail to the CSV file
        for (UserDetail ud : userDetailList) {
            String[] row = new String[] {
                ud.Id,
                String.join(ud.permissionSetList, ';'),
                ud.status
            };
            writer.writeNext(row);
        }
        
        // Close the writer to save the CSV file
        writer.close();
    }
    
    // ...
}

 
KRITI LAHA 8KRITI LAHA 8
Hello Shri Raj,

Thank you for the response. Even after adding the Apex Enterprise Patterns library to the org, I am getting failures like 'Invalid type: import', 'Invalid type: CSVWriter', 'Variable does not exist: writer' . Thanks