Running Reports in Apex

You can utilize the ReportManager class to run reports directly in Apex!

Did you know that you can use Apex to retrieve data from your database without using SOQL queries?

You can utilize the ReportManager class to run reports directly in Apex!

apex
Reports.reportResults res = Reports.ReportManager.runReport(reportId, true);

After running the report, you can retrieve the data from it. Check the next page for an example of how to get all values from a simple report without groupings

apex
Map<String, Reports.ReportFactWithDetails> rf =
    (Map<String, Reports.ReportFactWithDetails>)res.getFactMap();

for(Reports.ReportFactWithDetails rfwd : rf.values()) {
    // Retrieve all data rows from your report result
    List<Reports.ReportDetailRow> reportRows = rfwd.getRows();
    for(Reports.ReportDetailRow rr : reportRows) {
        List<Reports.ReportDataCell> rdCells = rr.getDataCells();
        System.debug('Row data: ');
        Integer dataCellCounter = 0;
        // Do something with every single field of the data row:
        for(Reports.ReportDataCell rdc : rdCells) {
            System.debug(
                'Column: ' + columns[dataCellCounter] +
                ', Label: ' + rdc.getLabel() +
                ', Value: ' + rdc.getValue()
            );
            dataCellCounter++;
        }
    }
}

This method is more complex than simply using SOQL queries, but in this case, no SOQL queries were used, and query record limits were not increased by even a single row.

Check the Reports Namespace reference in official documentation to explore the full potential of running reports in Apex.

Text and code were extracted from the original slide. Plain-text version of the whole catalog