Import using Apex in Salesforce

Visualforce page:


<apex:page controller="ImportCtrlr">
<apex:form >
<apex:pageblock >
<apex:pageBlockSection columns="2">
<apex:pageBlockSectionItem >
<apex:outputLabel value="Select Object"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:selectList size="1" value="{!obj}" >
<apex:selectOptions value="{!objs}"/>
</apex:selectList>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Select File"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:inputFile value="{!fileContent}" filename="{!fileName}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageblockButtons >
<apex:commandButton value="Import" action="{!importData}"/>
</apex:pageblockButtons>
</apex:pageblock>
</apex:form>
</apex:page>


Apex:

public class ImportCtrlr 
{
public Map<String, Schema.SObjectType> objs {get; set;}
public String obj {get;set;}
public Blob fileContent {get;set;}
public String filename {get;set;}
public List<List<String>> parsedCSVdata;
public List<sObject> sObjectDatatoStore;

public ImportCtrlr()
{
objs = Schema.getGlobalDescribe();
}

public void importData()
{
String fileString = fileContent.toString();
parsedCSVdata = parseCSV(fileString,false);
System.debug('Parsed CSV Data -->' + parsedCSVdata);
sObjectDatatoStore = csvTosObject(parsedCSVdata,obj);
System.debug('sObjectDatatoStore -->' + sObjectDatatoStore);
insert sObjectDatatoStore;
}

/* Method to parse CSV to List<List<String>> */
public List<List<String>> parseCSV(String contents,Boolean skipHeaders) 
{  

     List<List<String>> allFields = new List<List<String>>();  

     // replace instances where a double quote begins a field containing a comma  
     // in this case you get a double quote followed by a doubled double quote  
     // do this for beginning and end of a field  

     contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');  


     // now replace all remaining double quotes - we do this so that we can reconstruct  

     // fields with commas inside assuming they begin and end with a double quote  

     contents = contents.replaceAll('""','DBLQT');  


     // we are not attempting to handle fields with a newline inside of them  

     // so, split on newline to get the spreadsheet rows  

     List<String> lines = new List<String>();  


     try 

     {  
         lines = contents.split('\n');  
     } 
     catch (System.ListException e) 
     {  
         System.debug('Limits exceeded?' + e.getMessage());  
     }  

     Integer num = 0;  


     for(String line : lines)

{  

         // check for blank CSV lines (only commas)  


         if (line.replaceAll(',','').trim().length() == 0) break;             

         List<String> fields = line.split(',');      

         List<String> cleanFields = new List<String>();  


         String compositeField;  


         Boolean makeCompositeField = false;  


         for(String field : fields) 

         {  

             if (field.startsWith('"') && field.endsWith('"')) 

             {  
                 cleanFields.add(field.replaceAll('DBLQT','"'));  
             } else if (field.startsWith('"')) 
             {  
                 makeCompositeField = true;  
                 compositeField = field;  
             } 
             else if (field.endsWith('"')) 
             {  
                 compositeField += ',' + field;  
                 cleanFields.add(compositeField.replaceAll('DBLQT','"'));  
                 makeCompositeField = false;  

             } 

             else if (makeCompositeField) 
             {  
                 compositeField +=  ',' + field;  
             } 
             else 
             {  
                 cleanFields.add(field.replaceAll('DBLQT','"'));  
             }  
         }            
         allFields.add(cleanFields);  

     }  


     if (skipHeaders) allFields.remove(0);  


     return allFields;        
 

/* Method to parse List<List<String>> to sObject */
public list<sObject> csvTosObject(List<List<String>> parsedCSV, string objectType)
    {
        Schema.sObjectType objectDef = Schema.getGlobalDescribe().get(objectType).getDescribe().getSObjectType();
        System.debug('Object Definition --> ' + objectDef);
        
        list<sObject> objects = new list<sObject>();
        list<string> headers = new list<string>();
        
        for(list<string> row : parsedCSV)
        {
            for(string col : row)
            {
                headers.add(col);
            }
            break;
        }
        System.debug('Headers --> ' + headers);
        integer rowNumber = 0;
        for(list<string> row : parsedCSV)
        {
            if(rowNumber == 0)
            {
                rowNumber++;
                continue;
            }
            else
            {
                sObject thisObj = objectDef.newSobject();
                integer colIndex = 0;
                for(string col : row)
                {                   
                    string headerName = headers[colIndex].trim();
                    system.debug('========================= Column Name ' + headerName);
                    if(headerName.length() > 0)
                    {                  
                        try
                        {                       
                        if(col.contains('/'))
                        {
                        Date tempDate;
                        String[] tempStr = col.split('/');
                        Integer d = Integer.valueOf(tempStr[0]);
                        Integer m = Integer.valueOf(tempStr[1]);
                        Integer y = Integer.valueOf(tempStr[2]);
                        tempDate = Date.newInstance(y,m,d);
                        thisObj.put(headerName,tempDate);
                        }
                        else
                        {
                        thisObj.put(headerName,col.trim());
                        }                            
                        }
                        catch(exception e)
                        {
                            system.debug('============== Invalid field specified in header ' + headerName);                           
                        }
                        colIndex++;
                    }
                } 
                objects.add(thisObj);
                rowNumber++;
            }       
        }        
        System.debug('Object Data --> ' + objects);
        return objects;
    }
}

Cheers!!!

3 comments:

  1. Sir this is venkatesh,

    Import using Apex in Salesforce
    Sir i try this code in my login but the importing csv file is doesn't inserted in to the selected Sobjects .........

    ReplyDelete
  2. Replies
    1. sir i use .csv format but its not working....

      this is my debug log on the time of executing....

      27.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO
      22:49:37.045 (45431000)|EXECUTION_STARTED
      22:49:37.045 (45508000)|CODE_UNIT_STARTED|[EXTERNAL]|06690000002Rjhg|VF: /apex/pack_saleforce__Accuploadpage
      22:49:37.046 (46755000)|VF_DESERIALIZE_VIEWSTATE_BEGIN|06690000002Rjhg
      22:49:37.065 (65052000)|VF_DESERIALIZE_VIEWSTATE_END
      22:49:37.066 (66689000)|CODE_UNIT_STARTED|[EXTERNAL]|ImportCtrlr set(fileContent,Blob[168])
      22:49:37.066 (66708000)|SYSTEM_MODE_ENTER|true
      22:49:37.066 (66752000)|CODE_UNIT_STARTED|[EXTERNAL]|ImportCtrlr set(fileContent,Blob[168])
      22:49:37.066 (66844000)|METHOD_ENTRY|[1]|01p90000002UgZn|ImportCtrlr.ImportCtrlr()
      22:49:37.066 (66859000)|METHOD_EXIT|[1]|ImportCtrlr
      22:49:37.066 (66882000)|CODE_UNIT_FINISHED|ImportCtrlr set(fileContent,Blob[168])
      22:49:37.066 (66895000)|CODE_UNIT_FINISHED|ImportCtrlr set(fileContent,Blob[168])
      22:49:37.066 (66958000)|CODE_UNIT_STARTED|[EXTERNAL]|ImportCtrlr set(fileName,Account.csv)
      22:49:37.066 (66971000)|SYSTEM_MODE_ENTER|true
      22:49:37.066 (66985000)|CODE_UNIT_STARTED|[EXTERNAL]|ImportCtrlr set(fileName,Account.csv)
      22:49:37.067 (67015000)|CODE_UNIT_FINISHED|ImportCtrlr set(fileName,Account.csv)
      22:49:37.067 (67027000)|CODE_UNIT_FINISHED|ImportCtrlr set(fileName,Account.csv)
      22:49:37.073 (73738000)|CODE_UNIT_STARTED|[EXTERNAL]|01p90000002UgZn|ImportCtrlr get(objs)
      22:49:37.073 (73760000)|SYSTEM_MODE_ENTER|true
      22:49:37.073 (73773000)|CODE_UNIT_STARTED|[EXTERNAL]|01p90000002UgZn|objs
      22:49:37.073 (73790000)|CODE_UNIT_FINISHED|objs
      22:49:37.073 (73799000)|CODE_UNIT_FINISHED|ImportCtrlr get(objs)
      22:49:37.130 (130373000)|CODE_UNIT_STARTED|[EXTERNAL]|01p90000002UgZn|ImportCtrlr get(objs)
      22:49:37.130 (130406000)|SYSTEM_MODE_ENTER|true
      22:49:37.130 (130424000)|CODE_UNIT_STARTED|[EXTERNAL]|01p90000002UgZn|objs
      22:49:37.130 (130452000)|CODE_UNIT_FINISHED|objs
      22:49:37.130 (130462000)|CODE_UNIT_FINISHED|ImportCtrlr get(objs)
      22:49:37.140 (140080000)|VF_SERIALIZE_VIEWSTATE_BEGIN|06690000002Rjhg
      22:49:37.143 (143725000)|VF_SERIALIZE_VIEWSTATE_END
      22:49:37.750 (147095000)|CUMULATIVE_LIMIT_USAGE
      22:49:37.750|CUMULATIVE_LIMIT_USAGE_END

      22:49:37.147 (147129000)|CODE_UNIT_FINISHED|VF: /apex/pack_saleforce__Accuploadpage
      22:49:37.147 (147137000)|EXECUTION_FINISHED

      Delete