+ Start a Discussion
David Roberts 4David Roberts 4 

how to export country codes

A Trailblazer Community posting (https://success.salesforce.com/_ui/core/userprofile/UserProfilePage?u=00530000001sMqZ&tab=sfdc.ProfilePlatformFeed&fId=0D53A00004Y1vM9&s1oid=00D300000000iTz&emkind=chatterGroupDigest&s1nid=0DB30000000072L&emtm=1566722973622&s1uid=0053A00000DGqXQ&fromEmail=1&s1ext=0)led me to develop this handy solution for exporting the Country and State codes. Knowledge article 338321  (https://help.salesforce.com/articleView?id=000338321&type=1&mode=1) was the starting point.
Here's the Visualforce Page:
<apex:page controller="ExportToExcelController" readOnly="true" 
    action="{!fetchListOfCountryCodes}" contentType="application/vnd.ms-excel#{!fileName}.xls">
  <!-- https://help.salesforce.com/articleView?id=000338321&type=1&mode=1 -->  
    
    <table>
        <apex:repeat value="{!Countries}" var="cos">
            <tr>
            <td><apex:outputText>{!cos[0]}</apex:outputText></td>
            <td><apex:outputText>{!cos[1]}</apex:outputText></td>
            </tr>
        </apex:repeat>
        <tr></tr>
        <apex:repeat value="{!States}" var="st">
            <tr>
            <td><apex:outputText>{!st[0]}</apex:outputText></td>
            <td><apex:outputText>{!st[1]}</apex:outputText></td>
            </tr>
        </apex:repeat>
        
    </table>
    
</apex:page>

and the controller:
public class ExportToExcelController {
    
    public String fileName {get; set;}
    public List<List<String>> Countries {get; set;}
    public List<List<String>> States {get; set;}

    public void fetchListOfCountryCodes() {
        
        List<Schema.PicklistEntry> ple;
        fileName = 'countryandstatecodes';
        
        Countries = new List<List<String>>();
        Schema.DescribeFieldResult fieldResult = User.Countrycode.getDescribe();
        ple = fieldResult.getPicklistValues();
        //System.debug('Picklist::'+ple);
        for( Schema.PicklistEntry f : ple){
            
            List<String> aCountry = new List<String>();
            aCountry.add(f.getLabel());
            aCountry.add(f.getValue());
            
        	//System.debug(f.getLabel() +'::'+ f.getValue());
            Countries.add(aCountry);
        }
        
        States = new List<List<String>>();
        fieldResult = User.statecode.getDescribe();
        ple = fieldResult.getPicklistValues();
        //System.debug('Picklist::'+ple);
        for( Schema.PicklistEntry f : ple){
            
            List<String> aState = new List<String>();
            aState.add(f.getLabel());
            aState.add(f.getValue());
            
        	//System.debug(f.getLabel() +'::'+ f.getValue());
            States.add(aState);
        }
        
    }//fetchListOfCountryCodes
}//ExportToExcelController

​​​​​​​