Thursday, June 29, 2017

How to Read CSV file from Apex display in visualforce?

And MS word in visual force page?

I recently had to develop a Visualforce page that allowed a Salesforce user to upload a CSV file and then generate some records from the parsed values. Yes, I know that is what the Data Loader is for, but the intended user here was not technically adept. And I thought it was an interesting experiment.




Visualforce page: csvuploadVF

<apex:page sidebar="false" controller="FileUploader">
   <apex:form >
      <apex:sectionHeader title="Upload data from CSV file"/>
      <apex:pagemessages />
      <apex:pageBlock >
             <center>
              <apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
              <br/> <br/> <font color="red"> <b>Note: Please use the standard template to upload Accounts.</b> </font>
             </center>  
      
      
      <apex:pageblocktable value="{!uploadedAccounts}" var="acc" rendered="{!NOT(ISNULL(uploadedAccounts))}">
          <apex:column headerValue="Account Name">
              <apex:outputField value="{!acc.Name}"/>
          </apex:column>
          <apex:column headerValue="Shipping Street">
              <apex:outputField value="{!acc.ShippingStreet}"/>
          </apex:column>
          <apex:column headerValue="Shipping City">
              <apex:outputField value="{!acc.ShippingCity}"/>
          </apex:column>
          <apex:column headerValue="Shipping State">
              <apex:outputField value="{!acc.ShippingState}"/>
          </apex:column>
          <apex:column headerValue="Shipping Postal Code">
              <apex:outputField value="{!acc.ShippingPostalCode}"/>
          </apex:column>
          <apex:column headerValue="Shipping Country">
              <apex:outputField value="{!acc.ShippingCountry}"/>
          </apex:column>
      </apex:pageblocktable> 
      
      </apex:pageBlock>       
   </apex:form>   

</apex:page>


Apex Class:


public class FileUploader 

{
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    String[] filelines = new String[]{};
    List<Account> accstoupload;
    
    public Pagereference ReadFile()
    {
        nameFile=contentFile.toString();
        filelines = nameFile.split('\n');
        accstoupload = new List<Account>();
        for (Integer i=1;i<filelines.size();i++)
        {
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
            
            Account a = new Account();
            a.Name = inputvalues[0];
            a.ShippingStreet = inputvalues[1];       
            a.ShippingCity = inputvalues[2];
            a.ShippingState = inputvalues[3];
            a.ShippingPostalCode = inputvalues[4];
            a.ShippingCountry = inputvalues[5];

            accstoupload.add(a);

        }
        try{
        insert accstoupload;
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
            ApexPages.addMessage(errormsg);
        }    
        return null;
    }
    
    public List<Account> getuploadedAccounts()
    {
        if (accstoupload!= NULL)
            if (accstoupload.size() > 0)
                return accstoupload;
            else
                return null;                    
        else
            return null;
    }            

}


Finally then try to upload the sample file as below with CSV file format.





How to Generate MS-Word document using VF pages?



I have a VF which renders as MS-Word. for this you need to mention content type in <apex:page> tag. 

EX:-

<apex:page standardController="Account"  contentType="application/msword#sfdcsrini.doc" cache="true">

<html xmlns:w="urn:schemas-microsoft-com:office:word">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<body>
<apex:outputText title="Welcome to word" value="{!$User.FirstName}"/>
<br/>
<br/>
<apex:pageBlock >
<div style="text-align:left" >
<b>Account Name :</b><apex:outputText value="{!account.name}"/><br/>
<b>Account Number: </b><apex:outputText value="{!account.AccountNumber}"/><br/>
</div>            
</apex:pageBlock>
</body>
</html>


</apex:page>


once you save this code in to your vf page you need to pass the account id in to url like

https://c.ap1.visual.force.com/apex/worddocvf?id=0019000000RMAaF


 here contentType="application/msword#sfdcsrini.doc" tells that page should render as ms-word document.(sfdcsrini) is the name of the document in content type, you can give your own name. 



Checking for Object Accessibility in Visualforce page.


If a user has insufficient privileges to view an object, any Visualforce page that uses a controller to render that object will be inaccessible. To avoid this error, you should ensure that your Visualforce components will only render if a user has access to the object associated with the controller.


You can check for the accessibility of an object like this:
{!$ObjectType.objectname.accessible}

This expression returns a true or false value.
For example, to check if you have access to the standard Lead object, use the following code:
{!$ObjectType.Lead.accessible}

For custom objects, the code is similar:
{!$ObjectType.MyCustomObject__c.accessible}

where MyCustomObject__c is the name of your custom object.


<apex:page standardController="Lead">
<apex:pageBlock rendered="{!$ObjectType.Lead.accessible}">
<p>This text will display if you can see the Lead object.</p>
</apex:pageBlock>
<apex:pageBlock rendered="NOT({!$ObjectType.Lead.accessible})">
<p>Sorry, but you cannot see the data because you do not have access to the Lead object.</p>
</apex:pageBlock>
</apex:page>

No comments:

Post a Comment