I have csv file with account records and want to insert that records via apex. How can i do it and dynamically find necessary fields? I can only manually assign them and its hard to parse cause of their name in csv file (Account ID,Account Name,Account Type). I dont want to write : a.Name = inputvalues[1]; I want to retrive field-data from csv somehow.

So now it looks like that, but i want it to be more reusable

public static Account[] getAccountData(){
        StaticResource sr = [SELECT Id, Body FROM StaticResource WHERE Name = 'Account' LIMIT 1];
        String body = sr.Body.toString();
        String[] filelines = body.split('\n');
        String n = 'Account';
        List<Account>accs = new List<Account>();
        for (Integer i=1;i<filelines.size();i++)
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
            Account a = new Account();
            a.Name = inputvalues[1];
            a.Type = inputvalues[2];
        return accs;


Account ID,Account Name,Account Type
"0010900000oJcmQAAS","Sample Account for Entitlements",""
"0010900000pOqyQAAS","Edge Communications","Customer - Direct"
"0010900000pOqyRAAS","Burlington Textiles Corp of America","Customer - Direct"
"0010900000pOqySAAS","Pyramid Construction Inc.","Customer - Channel"

1 Answer 1


If you can change the header row to contain the field API names not label text then you can use code like this:

    String[] headings = filelines[0].split(',');
    for (Integer i = 1; i < filelines.size(); i++) {
        String[] values = filelines[i].split(',');
        Account a = new Account();
        for (Integer j = 0; j < values.size(); j++) {
            a.put(headings[j], values[j]);
    return accs;

but only if the data in the CSV is all strings as otherwise you will have to do some parsing based on type. Also note that text strings in CSV can include embedded commas and solving that problem is a bit awkward.

If you are stuck with the labels in the headings (and they are the actual labels in the org) you can use an object-level describe call to find all the fields on Account and then do a field level describe on each field to find the label that matches your headers, and get the field API name from the DescribeFieldResult.

  • Thanks, seems best way just to change header row.
    – Tirkocuyda
    Oct 20, 2021 at 15:33
  • Hi @Tirkocuyda, Yep. But do be aware of the embedded comma problem too.
    – Keith C
    Oct 20, 2021 at 16:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .