Skip to content

Instantly share code, notes, and snippets.

@yasarshaikh
Created February 26, 2019 11:24
Show Gist options
  • Save yasarshaikh/5777f69a6190e5699bb283b0564ff059 to your computer and use it in GitHub Desktop.
Save yasarshaikh/5777f69a6190e5699bb283b0564ff059 to your computer and use it in GitHub Desktop.
CSV Reader in Apex
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);
}
}
}
}
FirstName LastName Company
test1 1test 1comp1
test2 2test 2comp2
test3 3test 3comp3
@yasarshaikh
Copy link
Author

To execute the same-
CsvReader.readCsv('Lead_csvReader');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment