Tuesday, June 18, 2013

Apex - CSV File Reader

This code also includes way of handling double quotes that are part of CSV file. Although I myself have not used it but looking at the code, this seems to work pretty well. I know there are certain limitations of file max size and all those limitations are applied here also. This code just gives you a ready code to include in your implementation. All comments are welcome.

PS: I do not take any credit / responsibility of the code.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    /**
     * Returns a List containing Lists of Strings that represents
     * the values contained in the CSV file.
     *
     * Each element in the outer list represents a row in the CSV file.
     * Each element in the inner list is the value in the field specified
     * by the row-column combination. 
     * contents - contains file contents retrieved using <apex:inputFile value="{!contents}" />
     */
    public static  List<List<String>> parseCSV(String contents,String sep,Boolean skipHeaders) {  
    
        List<List<String>> allFields = new List<List<String>>();  
    
         // we are not attempting to handle fields with a newline inside of them  
         // so, split on newline to get the spreadsheet rows  
        List<String> lines = new List<String>();  
        try {  
            // TODO: Need to check for \r\n too
            lines = contents.split('\n');  
        } catch (System.ListException e) {  
             System.debug('Limits exceeded?' + e.getMessage());  
        }  
    
        Integer num = 0;  
        for(String line : lines) {  
    
            // check for blank CSV lines (only commas)  
            if (line.replaceAll(',','').trim().length() == 0) continue;  
            if(line.trim().length()==0) continue;
            
            //Replace the Separator with ','
            line = line.replace(sep,',');
            
            List<String> fields = line.split(',');      
            List<String> cleanFields = new List<String>();  
    
            String compositeField;  
            Boolean makeCompositeField = false;  
    
            for(String field : fields) {  
                field = field.trim();
                if (field.startsWith('"') && field.endsWith('"')) {  
                    cleanFields.add(field.replaceAll('"',''));  
                    makeCompositeField = false;
             } else if (field.startsWith('"')) {  
                    compositeField += ',' + field;  
                    makeCompositeField = true;
                    compositeField = field;  
                } else if (field.endsWith('"')) {  
                    compositeField += ',' + field;  
                    cleanFields.add(compositeField.replaceAll('"',''));  
                    makeCompositeField = false;  
                } else if (makeCompositeField) {  
                     compositeField +=  ',' + field;  
                } else {  
                     cleanFields.add(field.replaceAll('"',''));  
                }  
      
            }  
            allFields.add(cleanFields);  
         }  
         if (skipHeaders) allFields.remove(0);  
         return allFields;         
     }