+ Start a Discussion
Anshul Kapoor 13Anshul Kapoor 13 

Export the data in .csv file using Apex

VF-1:

apex:page controller="TwitterListApi" 
 apex:form 
apex:pageBlock
<br/><br/> <h1>
Please Press the button to get the List of Twitter Account Users</h1><br/><br/> 
apex:commandLink value="Submit" action="{!Submit}" target="_blank" styleClass="btn"/
/apex:pageBlock
/apex:form
/apex:page

VF-2:

apex:page controller="TwitterListApi" showHeader="false" sidebar="false" action="{!generatecsv}" contentType="application/octet-stream#Twitter_Acoount Information.csv">User Name, Name, Location, Mobile
    apex:repeat value="{!Generate}"
       {!screenname}, {!username}, {!location}, {!mobile}
    /apex:repeat
  /apex:page
Apex Code:

public class TwitterListApi
{
    public String oAuthConsumerKey = 'BlsoC839h5czptk6oHyyAgTGq';
    public String oAuthConsumerSecret = 'iAF4rc2AFEOP1h9rNVx4ZM8B86GXo4IGPcl2DN67iiMi6mdxnu';
    public String oAuthUrl = 'https://api.twitter.com/oauth2/token';
    public String oAuthUrl_1 = 'https://api.twitter.com/1.1/users/lookup.json?screen_name=';
    public String username{get;set;}
    public String location{get;set;}
    public String mobile{get;set;}
    public String screenname{get;set;}
    public String stoken;
    public List<Companies> list_com;
           
    
    public pageReference Submit()
    {
        pageReference pageRef= new pageReference('/apex/GenerateListApi');
        pageRef.setRedirect(true);
        pageRef.setRedirect(false);
        return pageRef;
    }
    
    public pageReference generatecsv()
    {
         String name;
         List<username__c> list_user;
        try
        {
            list_user=[select name__c from username__c];
        }
        catch (System.QueryException e)
        {
            system.debug('Error in generatecsv method for list_user query** '+e);
        }
        for (username__c user:list_user)
        {  
           if (name==null)
           {
              String url=EncodingUtil.urlEncode(user.name__c,'UTF-8');
               name=url;               
           }
           else 
           {
               String url=EncodingUtil.urlEncode(user.name__c,'UTF-8');
               name=name+','+url;
           }
        }
        system.debug('name** '+name);
        //Encode them
        String keyencoded = EncodingUtil.urlEncode(oAuthConsumerKey, 'UTF-8');
        String secretkeyencoded = EncodingUtil.urlEncode(oAuthConsumerSecret, 'UTF-8');

        //Create Final Key String
        String sFinal = keyencoded + ':' + secretkeyencoded;
        //Convert to Blob
        Blob headerValue = Blob.valueOf(sFinal);
        system.debug('headerValue** '+headerValue);

        //Build Request
        HttpRequest req = new HttpRequest();
        req.setEndpoint(oAuthUrl);
        req.setMethod('POST');

        //Add Auth Header
        String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
        req.setHeader('Authorization', authorizationHeader);
        system.debug('authorizationHeader** '+authorizationHeader);

        //You need to add this to the request - proved easy to miss in instructions...
        req.setBody('grant_type=client_credentials');

        //Make request
        Http http = new Http();
        try{
        HTTPResponse res = http.send(req);
        system.debug('Body_1** '+res.getBody());           
        //String stoken;
        //Parse JSON for Bearer Token
        
        JSONParser parser = JSON.createParser(res.getBody());
        while (parser.nextToken() != null) {
        if (parser.getCurrentToken() == JSONToken.FIELD_NAME && parser.getText() == 'access_token'){
        parser.nextToken();
        stoken = parser.getText();
        }
        }
        }
        catch(System.CalloutException e)
        {
            system.debug('Error_1** '+e.getMessage());
        }
        
     
    HttpRequest req2 = new HttpRequest();
    //I actually store the endpoint in the same custom setting and build dynamically, but for purposes of demo:
        req2.setEndpoint(oAuthUrl_1 + name);
        req2.setMethod('GET');

    //Call Bearer token Method
    //Note - unless invalidated, I believe you can store this and keep using it indefinitely, but again, to demo concept
    String authorizationHeader_1 = 'Bearer ' + stoken;
    req2.setHeader('Authorization', authorizationHeader_1);
    system.debug('authorizationHeader_1** '+ authorizationHeader_1);

    try{
    HTTPResponse res = http.send(req2);
    String sBody = res.getBody();
    system.debug('Body_2** ' + sBody);
    boolean success=true;
    JSONParser parser=JSON.createparser(res.getBody());
    while (parser.nextToken()!=null)
    {
        if(parser.getCurrentToken()== JSONToken.START_OBJECT)
        {    
            while (parser.nextToken()!=null)
            {
                if((parser.getCurrentToken()==JSONToken.FIELD_NAME) && (parser.getText()=='screen_name'))
                {
                    parser.nextToken();
                    screenname=parser.getText();
                    system.debug('screenname** '+screenname);
                    success=true;
                }
                
                if((parser.getCurrentToken()==JSONToken.FIELD_NAME) && (parser.getText()=='name')) 
                {
                    parser.nextToken();
                    username=parser.getText();
                    system.debug('username** '+username);
                }
                
                integer i = 0;
                
                if((parser.getCurrentToken()==JSONToken.FIELD_NAME) && (parser.getText()=='location'))
                {
                    parser.nextToken();
                    location=parser.getText();
                    location = '"'+location+'"';
                    system.debug('location** '+location );
                }
                
                if (success)
                {
                    if ((parser.getCurrentToken()==JSONToken.FIELD_NAME) && (parser.getText()=='description'))
                    {
                        parser.nextToken();
                        mobile=parser.getText();
                        success=false;
                        system.debug('mobile** '+mobile);
                        List<Companies> list_com=new List<Companies>();
                        Companies com=new Companies(screenname, username, location, mobile);
                        system.debug('com** '+com);
                        list_com.add(com);
                        system.debug('list_com-1** '+list_com);
                    }
                 }
                 
            }
        }
    }
    }
    catch(System.CalloutException e)
    {
        system.debug('Error_2** '+e.getMessage());
    }
        return null;
    }
    
    public List<Companies> getGenerate()
    {
        system.debug('list_com** '+list_com);
        return list_com;
    }
    
    public class Companies
    {

        String screenname;
        String username;
        String location;
        String mobile;
        
        
        public  Companies(String screename, String username, String location, String mobile)
        {
             this.screenname=screenname;
             this.username=username;
             this.location=location;
             this.mobile=mobile;   
        }
    }
}

Q1 I am getting null in list_com in a method  getGenerate().

Please solve my query?
Kevin AkermanisKevin Akermanis
You page ContentType looks wrong....  just set it to text/csv
Also... you probably want to edit your original post and delete your Twitter Consumer keys and secrets.....
Anshul Kapoor 13Anshul Kapoor 13
contentType is right. I wanted to generate the excel of the users containing information about the user`s location, name & mobile no
Kevin AkermanisKevin Akermanis
You're attempting to use the action attribute to initialise your various objects which you're not supposed to do - see Visualforce doco and look at the action attribute: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_compref_page.htm

Check out this thread on stackExchange - that should point you in the right direction:
http://salesforce.stackexchange.com/questions/23923/call-apex-method-from-visual-force-page-not-in-constructor

 
Anshul Kapoor 13Anshul Kapoor 13
@Kevin, I wanted to generate .csv file. I have used this code, everything works fine. But, I am not able to manipulate to generate .csv file. Could u help me to correct the code for  the same. 
Anshul Kapoor 13Anshul Kapoor 13
Please follow the link to get the answer: https://developer.salesforce.com/forums/ForumsMain?id=906F0000000BPwiIAG