Created
February 26, 2019 11:24
-
-
Save yasarshaikh/5777f69a6190e5699bb283b0564ff059 to your computer and use it in GitHub Desktop.
CSV Reader in Apex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CsvReader { | |
public static void readCsv(String fName){ | |
if(fname != NULL){ | |
try{ | |
StaticResource sr = [select id, body from StaticResource where name=: fName]; | |
Lead lobj; | |
List<Lead> lLead = new List<lead>(); | |
if(sr.body != NULL){ | |
String sCSV = sr.body.toString(); | |
List<String> lstFieldNames = new List<String>(); | |
List<String> dataLines = sCSV.split('\\n'); | |
Map <String, Integer> fieldNumberMap = new Map < String, Integer > (); | |
string[] csvFieldNames = dataLines[0].split(','); | |
for (Integer i = 0; i < csvFieldNames.size(); i++) { | |
fieldNumberMap.put(csvFieldNames[i], i); | |
lstFieldNames.add(csvFieldNames[i].trim()); | |
} | |
system.debug('dataLines ' +dataLines); | |
for (Integer i = 1; i < dataLines.size(); i++) { | |
lobj = new Lead(); | |
string[] csvRecordData = dataLines[i].split(','); | |
for (String fieldName: csvFieldNames) { | |
Integer fieldNumber = fieldNumberMap.get(fieldName); | |
String fieldValue = csvRecordData[fieldNumber]; | |
lobj.put(fieldName.trim(), fieldValue.trim()); | |
} | |
lLead.add(lobj); | |
} | |
} | |
if(lLead.size() > 0 ){ | |
insert lLead; | |
} | |
} | |
catch(QueryException qe){ | |
System.debug('QE: '+ qe); | |
} | |
catch(Exception e){ | |
System.debug('EE: ' + e); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FirstName | LastName | Company | |
---|---|---|---|
test1 | 1test | 1comp1 | |
test2 | 2test | 2comp2 | |
test3 | 3test | 3comp3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To execute the same-
CsvReader.readCsv('Lead_csvReader');