You need to sign in to do that
Don't have an account?
venkatsforce
Upload csv file data to SObjects
If I upload a csv file and I want to insert that csv file data s in to Account object, I create a code but i got some errors. If I load 2 columns in csv and add 5 columns in apex class but i got a exception Array Index Out of Bound Exception
Apex class
========
public class FileUploader { String[] filelines = new String[]{}; public List<Account> contoupload; public Blob contentFile { get; set; } public String nameFile { get; set; } public PageReference ReadFile() { System.Debug('Entry123'); nameFile=contentFile.toString(); System.Debug('nameFile123'+nameFile); filelines = nameFile.split('\n'); contoupload = new List<Account>(); for(Integer i=1;i<filelines.size();i++) { System.Debug('Values12313'+filelines.size()); String[] inputvalues = new String[]{}; inputvalues = filelines[i].split(','); Account a = new Account(); a.Name = inputvalues[0]; System.Debug('InputValues'+a.Name); a.Phone = input values[1]; a.Shipping Street = inputvalues[2]; a.ShippingCity = inputvalues[3]; a.ShippingState = inputvalues[4]; a.ShippingPostalCode = inputvalues[5]; a.ShippingCountry = inputvalues[6]; contoupload.add(a); System.Debug('Account Entry'+contoupload.size()); } try { if(contoupload.size()>0) { insert contoupload; System.Debug('FileSize12311'+contoupload.size()); } } catch (Exception e) { ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later'); ApexPages.addMessage(errormsg); } PageReference pg = new PageReference('https://csesparks-dev-ed--pack-saleforce.ap1.visual.force.com/apex/Fileupload'); pg.setRedirect(true); return pg; } }
Error like this:
System.ListException: List index out of bounds: 2
Ofcourse, it will throw an error because of the followed block
If you split a row of CSV file, you get an array of size 2. Hence, inputvalues[0] and inputvalues[1] will have some some values stored in them and it (2) will be max index can be used.
But here you are attempting to access the array index, which is greater than the max index of the array.
I think you got the key point here that I'm trying to convey here.