+ Start a Discussion
Amit Jadhav 13Amit Jadhav 13 

Can is it possible when we insert csv lead file using apex class if the insertion in fail the show the which csv file row fail when inserting record in salesforce and store row number in salesforce object

Can is it possible when we insert CSV lead file using apex class if the insertion in fail the show the which CSV file row fails when inserting a record in Salesforce and store row number in salesforce object
Sunad RasaneSunad Rasane
Hi Amit,
Please try the following code-

public string csvAsString;
public string[] csvFileLines; // now inside the constructor do this

public void importCsvFile(Blob bfile){
csvAsString = bfile.toString() ; //convert the blob into a string file
csvFileLines = csvAsString.split('\n'); //split the string file lines so //records/rows can be accessible
}

Let me know if this helps and make sure to mark it as the best answer so it helps others.
Thanks
Amit Jadhav 13Amit Jadhav 13
Hey Sunad 

Thanks for replying above logic are very helpful for me but I have one question if Multiple rows failed when inserting then how will to store in the database because in the log the only first logs come out.
Sunad RasaneSunad Rasane
Hi Amit,

Once you get details in csvFileLines , iterate over it and create records and add it in the list. After adding it in list use DataBase.Insert to dynamically insert data and make sure you use Database.SaveResult. Please refer-https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_database_saveresult.htm

List<Account> accts = new List<Account>();
Database.SaveResult[] srList = Database.insert(accts, false);
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted account. Account ID: ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors                
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}

I hope it helps. Thanks.
Amit Jadhav 13Amit Jadhav 13
Hey Sunad 

I was Tried this one also but we not getting row number in above code all error are getting except row number