Sunday, February 28, 2016

DataLoader: Loading Data Values using TXT files in Salesforce

Occassionally you might run into a situation where DataLoader will not work for you to load data in Salesforce. DataLoader typically works with only CSV files.

XL has a limitation of showing data in CSV after I think 15-16 chars, so if you want to load CreditCards or Gift cards which have 16 digits from a CSV file then you end seeing exponential numbers in XL i,e, something like 6.05E+9.

Solution

You can use the power of APEX to load data in TXT file format.

You need 2 things:
a) a Visual Force form to be able to select file from your desktop
b) a Controller Class to load data

//Start of Visual Force
<apex:page controller="XXX">
<body>
<center>
    <b><font size="15"><h1>Gift Card Master Data Load Form</h1></font></b><br/>
    <font size="2">1. Download the Vendor file and format in the appropriate txt file format.</font><br/>
    <font size="2">2. Click on the 'Choose File' button file below and select the file.</font><br/>
    <font size="2">3. Click on the 'Load Cards Data' to load data.</font><br/>
   
<p/>

<apex:form >

<apex:tabPanel >
<apex:tab >
<apex:inputfile value="{!fileBody}"/>
<apex:commandButton value="Load Cards Data" action="{!readContent}"/>
</apex:tab></apex:tabPanel>


</apex:form>
</center>
</body>
</apex:page>

                   
//End of Visual Force

Next, is the class to load the file:

//Start of Controller Class
public with sharing class XXX{
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    public blob fileBody { get; set; }

    String[] filelines = new String[]{};
    List<ObjName> ObjVar1;
   
public void readContent() {
      nameFile=fileBody.toString();
        filelines = nameFile.split('\n');
        GCtoupload = new List<ObjName>();

    for(Integer i=0;i<filelines.size();i++)
    {
   
      String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
           
            ObjName Var= new ObjName();
            Var.Fld1= inputvalues[0];
            Var.Fld2= inputvalues[1];      
        
        ObjVar1.add(Var);
       
    }

   try{
   insert ObjVar1;
   
   } catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the file and try again later.');
            ApexPages.addMessage(errormsg);
        }   
}
        
}
//End of Controller Class

Here is the file format I used:

D000493500555389448,10.23,
D006493500555389455,11.23,
D006493500553798426,10


No comments:

Post a Comment