I am uploading CSV file using <apex:inputfile>
in vf page.
CSV file contains 4 columns.
Scenario 1) When I try to upload a file without comma in any column, It gets uploaded without any error.
Scenario 2) When I try to upload a file with comma present inside column, It gives an error and doesn't get uploaded.
Then I realized that it considers text/data after comma as next column.
How can I avoid or tackle this error.
Below is my function :-
public Pagereference ReadFile()
{
if(contentFile!=null){
sourceid = ApexPages.currentPage().getParameters().get('id');
nameFile= blobToString(contentFile,'ISO 8859-1');
// nameFile = contentFile.toString();
filelines = nameFile.split('\n');
importupload = new List<ZIS_Quote_Source__c>();
for (Integer i=1;i<filelines.size();i++)
{
String[] inputvalues = new String[]{};
inputvalues = filelines[i].split(',');
ZIS_Quote_Source__c a = new ZIS_Quote_Source__c();
a.Item__c = inputvalues[0];
String temp1;
String temps =inputvalues[1].replaceAll('""','@SpaceStation');
temps =temps.replaceAll('"','');
temp1 = temps.replaceAll('@SpaceStation','"');
IF(temp1.length() >= 250){
a.Item_Description__c = temp1.substring(0,249);
}
else{
a.Item_Description__c = temp1;
}
a.Full_Description__c = temp1;
a.UOM__c = inputvalues[2];
a.Final_Req__c = Double.valueof(inputvalues[3]);
a.Grouping__c = inputvalues[4];
a.ZISQuote__c = sourceid;
importupload.add(a);
}
}
try{
insert importupload;
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Quote Source/s inserted successfully'));
}
catch (Exception e)
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check or try again later');
ApexPages.addMessage(errormsg);
}
return null;
}
Help would be greatly appreciated.
Tia
Best Answer
FWIW, this is a CSV parser with testmethods that I located from a blog post (which no longer exists) - There could easily be better ways of doing this but it handles embedded commas and double quotes. Code is ca. 2011. I've used this before