+ Start a Discussion
sfadm sfadmsfadm sfadm 

CSV file upload validation

In the following piece of code:
List<String> necessaryColumns = new List<String> {'columnA', 'columnB', 'columnC', 'columnD', 'columnE', 'columnF','columnG'};    
Set<String> columnsInFile = new Set<String>(necessaryColumns);
            System.debug('columnsInFile' + columnsInFile);
            // Get all column names from the CSV file
            List<String> columnNames = csvRecords.get(0);
            for(String columnName :columnNames) {
                System.debug('columnName: ' + columnName);
                if(!columnsInFile.contains(columnName)) {
                    System.debug('clmnName: ' + columnName);
                    ApexPages.Message myMessage = new ApexPages.Message(ApexPages.Severity.FATAL, 'The uploaded file is invalid');
                    ApexPages.addMessage(myMessage);
                    return;      
                }
            }
The issue I have is that the names of the columns in the set are in strict order.
|DEBUG|columnsInFile{columnA, columnB, columnC, columnD, columnE, columnF, columnG}
and if the order of the columns in the CSV file is changed for instance:
columnG, columnF, columnD, columnC, columnA, columnB
The algorithm is entering the if block and is showing the message, which is totally wrong.
What I'm trying to achieve is to show the message only if one of the columns in the CSV file is missing.
If there are 20 columns in the CSV file but for instance columnA is missing in the file only then the ApexPages.Message has to be displayed for the users.
Please advise how this can be achieved with apex?


 
Best Answer chosen by sfadm sfadm
Dev_AryaDev_Arya
considering your csv file is correct, could you also post the output of line 7 where you are print the column name from the file. It could be the header from csv has quotes around it. Its just a guess. 

All Answers

Dev_AryaDev_Arya
considering your csv file is correct, could you also post the output of line 7 where you are print the column name from the file. It could be the header from csv has quotes around it. Its just a guess. 
This was selected as the best answer
sfadm sfadmsfadm sfadm

@Dev_Arya, as requested here is the output for line 07:

|DEBUG|columnName: columnA
|DEBUG|columnName: columnB
|DEBUG|columnName: columnC
|DEBUG|columnName: columnD
|DEBUG|columnName: columnE
|DEBUG|columnName: columnF
|DEBUG|columnName: columnG

However the output for line 09:

|DEBUG|clmnName: columnG
If I manually change the order of the columns in the following order:
columnA, columnF, columnD, columnC, columnG, columnB
The output for line 09 is:
|DEBUG|clmnName: columnF
Please advise and appropriate solution to this issue.


 
Dev_AryaDev_Arya
hi sfadm,

Appologies, i could not look in to it, got stuck with our own org issues. :-P
Could you figure this out so far, else we can look in to it? As a matter of curiosity, I would really like to know the use case.

Cheers,
Dev