Wednesday 1 October 2014

CSV File Data Import In Salesforce Apex

CSV File Data Import In Salesforce Apex(upload csv).importing data

Here I am going to share some piece of code. Which is use full to import csv file data in salesforce. In my case I need to import bank statement csv file data in custom object. So here I am processing csv data in batch process and inserting in sobject.

Here I am using  Batch process in following manner

 global Iterable<string>  start(Database.BatchableContext BC)
   {
   }

 So I am creating a  CSVIterator class. By using this Process I am not facing 'Regex too complicated’ error for large volume of data.

global with sharing class CSVIterator implements Iterator<string>, Iterable<string>
{
   private String m_CSVData;
   private String m_introValue;
   public CSVIterator(String fileData, String introValue)
   {
      m_CSVData = fileData;
      m_introValue = introValue;
   }
   global Boolean hasNext()
   {
      return m_CSVData.length() > 1 ? true : false;
   }
   global String next()
   {
      String row = m_CSVData.subString(0, m_CSVData.indexOf(m_introValue));
      m_CSVData = m_CSVData.subString(m_CSVData.indexOf(m_introValue) + m_introValue.length(),m_CSVData.length());
      return row;
   }
   global Iterator<string> Iterator()
   {
      return this;
   }
}


HERE I am using Database.Stateful in batch because I don't want to reset static variables in batch process.

 global class UploadBankStatementBatch implements Database.Batchable<string>, Database.Stateful
{

   global final blob dataDocuments;
   id BankAccountId;
   id CompanyId;
   BankStatement__c statement;
   global UploadBankStatementBatch (blob data,id BankAccountId,id CompanyId)
   {
             this.dataDocuments=data;
             this.BankAccountId=BankAccountId;
             this.companyId=companyId;
   }

   global Iterable<string>  start(Database.BatchableContext BC)
   {
       string nameFile=this.dataDocuments.toString();
       List<BankStatementLineItem__c> accstoupload = new List<BankStatementLineItem__c>();
     
        statement=new BankStatement__c();
        statement.name='import'+date.today();
        statement.BankAccountId__c=BankAccountId;
        statement.companyId__c=companyId;
        insert statement;
        system.debug(' Batch started bankStatment new created '+statement.id);
      return new CSVIterator(this.dataDocuments.toString(), '\n');
   }

   global void execute(Database.BatchableContext BC,List<String> scope)
   {
       //integer i=0;
       List<BankStatementLineItem__c> lst=new list<BankStatementLineItem__c>();
        for(String row : scope)
       {

         List<String> fields = row .split(',');
         IF(fields[0]!='*Date')
         {
             BankStatementLineItem__c li=new BankStatementLineItem__c();
         
             li.date__C=date.parse(fields[0]);
             IF(fields[1]!='')
             {
                li.Amount__c=decimal.valueof(fields[1]);
             }ELSE
             {
                li.Amount__c=0;
             }
             li.Payee__c=fields[2];
             li.Description__c=fields[3];
                 li.Status__c='open';
                 li.companyId__c=companyId;
                // li.CompanyId__C='';
                li.BankStatementId__c=statement.id;
              lst.add(li);

              }
       }
       insert lst;

   }

   global void finish(Database.BatchableContext BC){
 
     system.debug(' Batch finish bankStatment new created '+statement.id);
   }

 
 
}




Have a Good Day :)

3 comments:

  1. Hi ,
    It's really helpful.
    Can you please help me out. It getting error "First error: Ending position out of bounds: -1" i CSVIterator Class.

    please help me.

    Thanks.

    ReplyDelete
    Replies
    1. I keep running into this same issue. If someone was able to figurate that out it will be really helpfull.

      Delete
  2. How to identify the row numbers of this csv ?
    I want to identify the Headers and thereby the fields
    can you help on this.?

    ReplyDelete