+ Start a Discussion
Prince VenkatPrince Venkat 

Read csv file and insert records through batch apex

Hi
document obj contains a csv file
it should be read by batch apex and records shoud be inserted into an object
Best Answer chosen by Prince Venkat
Ashvin JAshvin J
Refer below code. 

Document doc = [Select Id,body from Document where id = '0152w000000NCIp'];
String stringBody = doc.body.tostring();
list<String> filelines = stringBody.split('\n');
list<Account> accstoInsert = new list<Account>();
for (Integer i=1;i<filelines.size();i++)
{
    list<String> columnValues = new list<String>();
    columnValues = filelines[i].split(',');
    system.debug('->'+columnValues);
    Account a = new Account();
    a.Name = columnValues[0];
    a.SLASerialNumber__c = columnValues[1];
    accstoInsert.add(a);
}
if(accstoInsert.size()>0){
    insert accstoInsert;
}

You can mention Document query in Start method and in execute method can perform rest of the logic. Make sure to change the Object and its fields you want to insert. 

Thanks,
Ashvin
 

All Answers

Ashvin JAshvin J
Hi Prince, 

Can you please elaborate on what you want to achieve ?  Do you want to read a CSV file and based on row values formulate a custom object record ?

Regards,
Ashvin
Ashvin JAshvin J
Refer below code. 

Document doc = [Select Id,body from Document where id = '0152w000000NCIp'];
String stringBody = doc.body.tostring();
list<String> filelines = stringBody.split('\n');
list<Account> accstoInsert = new list<Account>();
for (Integer i=1;i<filelines.size();i++)
{
    list<String> columnValues = new list<String>();
    columnValues = filelines[i].split(',');
    system.debug('->'+columnValues);
    Account a = new Account();
    a.Name = columnValues[0];
    a.SLASerialNumber__c = columnValues[1];
    accstoInsert.add(a);
}
if(accstoInsert.size()>0){
    insert accstoInsert;
}

You can mention Document query in Start method and in execute method can perform rest of the logic. Make sure to change the Object and its fields you want to insert. 

Thanks,
Ashvin
 
This was selected as the best answer
Prince VenkatPrince Venkat
Hi ashvin
It is working perfectly well
but not able to pass date datatype
a.Startdate__c = date.valueof(columnValues[1]); or a.Start__datec = date.parse(columnValues[1]);
tried different ways in csv file also with different dates how to reslove it

thanks in advance
 
sree sinhasree sinha
Hi Venkat,

i have similar use Case, Can you please post whole Batch class for my reference?