function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Swamy PSwamy P 

Parsing CSV File....List index out of bounds:

Hello Everyone,

I'm working on Parsing CSV File by "Apex". I'm facing an error "List index out of bounds: 1", I understand the error that I'm accessing which Is not having any value but I'm unable to get the solution. Below is my requirement and code which I'm trying to parse, please check it and update me where I can change.

Requirement: From ExcelColumn1 & Column2 needs to be Mapped for different Rows, like that Column5 & Column8 needs to be Mapped.

for(list<string> line:parsedCSV){                                  
       if(line[1]!=''&& line[1]!=null && line[2]!='' && line[2]!=null){
           lineMap.put(line[1],line[2]); -->Error Line - Sometimes error appearing here
       } 
       System.Debug(' lineMap..'+ lineMap);
       if(line[1]!='' && line[5]!='' && line[1]!=null && line[5]!=null){
           lineMap.put(line[1],line[5]);  -->Error Line - Sometimes error appearing here
       }       
}     
In "parsedCSV" list I'm getting all of the ROWS, Also in debug logs I'm able to see some of the values which are captured in LineMap.

As i know that we can fix this issue without passing hard-coded numbers in Arrays but as per the requirement I've to implement it in this way, If anyone knows anyother solution, Please update me. Thanks in Advance!!!!!

Any Suggestion will be Appreciated.
Magesh Mani YadavMagesh Mani Yadav
Hi Swamy,

May be the parsedCSV is returning list with size 1 for some List. Have you tried putting debug log for variable "line".
And also try the below example may be it helps for you.
StaticResource csvFile = [Select  s.Body From StaticResource s where s.Name LIKE :csvFileName];
String contentFile = (csvFile.Body).toString();
List<String> fileLines = contentFile.split('\n');
for (String fileLine : fileLines){ 
	List<String> columnData = filelines[i].split(';');
	System.debug('number of columns in each line: '+columnData.size());
}