[SalesForce] How to get a report to return more than 2,000 rows using the “ReportResults” class in the “Reports” namespace

Using cues from the sample here:

Sample in Salesforce Documentation

and the tutorial here:

Blog by Modelit with great sample

I wrote some code to go through a report in which the first column is always the id of the contact, and create campaign members based off of those values.

This works fine for reports that contain less than 2,000 results. But I can't get it to return more than 2,000 results.

I tried using the getAllData() method from the ReportResults class, but it just returns false… I'm not sure why.

Can anyone give me a pointer on how to run the report programmatically so that it returns all data?

Here's the anonymous code I'm using.

//Add variables here:
        id campaignId ='701E0000000blYG';
        String userSetStatus='Sent';
        id reportId = '00OE0000003BncO';

// Run a report synchronously
        Reports.reportResults ActiveISOContacts = Reports.ReportManager.runReport(reportId, true);
        ActiveContacts.getAllData();
        System.debug('Value of ActiveContacts.getAllData()' + ActiveContacts.getAllData());


        // Get the fact map from the report results
        Reports.ReportFactWithDetails factDetails = 
        (Reports.ReportFactWithDetails)ActiveContacts.getFactMap().get('T!T');

        //create a list of report rows and populate it with the result rows from fact map
        List<Reports.ReportDetailRow> reportRows = factDetails.getRows();
        System.debug('Value of reportRows.size()' +reportRows.size());

        //create a list of campaign memebers. To be populated in the for loop with contacts.
        List<CampaignMember> campaignmembers = new List<CampaignMember>();
        //loop through each report detail row and create a campaign member


        for(Reports.ReportDetailRow reportRow : reportRows){

            List<Reports.ReportDataCell> datacells = reportRow.getDataCells();
            Reports.ReportDataCell datacell = datacells[0];
            id conid = (id)datacell.getValue();
            CampaignMember campaignmember = new CampaignMember(CampaignId=campaignId,ContactId=conid,Status=userSetStatus);
            campaignmembers.add(campaignmember);

        }
        database.insert(campaignmembers,false);

Thanks!

Best Answer

The documentation is fairly explicit here:

The API returns up to the first 2,000 report rows. You can narrow results using filters.

You'll need to execute your report multiple times, using filters that you can guarantee will return fewer than 2000 rows (such as by using date ranges, report run #1 uses THIS_QUARTER, run #2 uses LAST_QUARTER, or you use first letter of name starts with A on run #1, then B on run #2)