Untitled

mail@pastecode.io avatar
unknown
plain_text
17 days ago
2.1 kB
1
Indexable
Never
// ID of the report you want to process to CSV
String reportId = 'yourReportId';

// Method to get the report in CSV format
public static String getReportAsCSV(String reportId) {
    // Initialize the report instance
    Reports.ReportInstance reportInstance = Reports.ReportManager.runReport(reportId, true);
    
    // Wait for the report to be ready
    while (reportInstance.getStatus() == Reports.ReportStatus.Pending || reportInstance.getStatus() == Reports.ReportStatus.InProgress) {
        // Re-fetch the report after a short delay
        reportInstance = Reports.ReportManager.getReportInstance(reportInstance.getId());
    }

    // Check if the report was generated successfully
    if (reportInstance.getStatus() == Reports.ReportStatus.Success) {
        // Get the report results
        Reports.ReportResults reportResults = Reports.ReportManager.getReportResults(reportInstance.getId());

        // Convert the report results to CSV
        return convertReportResultsToCSV(reportResults);
    } else {
        // Error handling if the report was not generated successfully
        throw new ApexException('Error generating the report: ' + reportInstance.getStatus());
    }
}

// Method to convert report results to CSV
public static String convertReportResultsToCSV(Reports.ReportResults reportResults) {
    // Build the CSV header
    String csv = '';
    for (Reports.ReportColumn column : reportResults.getReportMetadata().getDetailColumns()) {
        csv += '"' + column.getLabel() + '",';
    }
    csv = csv.removeEnd(',') + '\n';

    // Add the data rows to the CSV
    for (Reports.ReportFactWithDetails details : reportResults.getFactMap().values()) {
        for (Reports.ReportDataRow row : details.getRows()) {
            for (Reports.ReportDetailRowValue detailValue : row.getDataCells()) {
                csv += '"' + detailValue.getLabel() + '",';
            }
            csv = csv.removeEnd(',') + '\n';
        }
    }

    return csv;
}

// Run the method in anonymous mode
System.debug(getReportAsCSV(reportId));
Leave a Comment