將編頁報表導出至檔案

exportToFile API 可讓您使用 REST 呼叫匯出 Power BI 編頁報表。 支援下列檔案格式:

  • .pptx (PowerPoint)

  • .pdf (和無障礙 PDF 或 PDF/UA

  • .xlsx (Excel)

  • .docx (Word)

  • 。Csv

  • .xml

  • .mhtml

  • 映像
    匯出至影像時,請透過 OutputFormat 格式設定來設定影像格式。 支援的 OutputFormat 值為:

    • .tiff (預設值)
    • 。Bmp
    • 。Emf
    • .gif
    • .jpeg
    • .png

使用範例

您可以使用各種方式的匯出功能。 以下提供幾個範例:

  • 傳送至列印按鈕 - 在您的應用程式中,建立按兩下時觸發匯出作業的按鈕。 作業可以將檢視的報表導出為 .pdf 或 .pptx。 完成時,使用者可以以下載的形式接收檔案。 您可以使用報表參數和格式設定,以特定狀態匯出報表,包括篩選的數據、自定義頁面大小和其他格式特定設定。 因為這是非同步 API,所以可能需要一些時間,檔案才能使用。

  • 電子郵件附件 - 使用附加的 .pdf 報表,依設定間隔傳送自動電子郵件。 如果您想要將每周報告自動傳送給主管,此案例會很有用。

使用 API

授權需求

  • 您導出的報表必須位於 進階版、Embedded 或 Fabric 容量支援的工作區中。
  • API exportToFile 在 進階版 每個使用者 (PPU)具有有限的支援

轉譯事件

若要確定導出不會在視覺效果完成轉譯之前開始,請使用 「轉譯」事件 API ,而且只有在轉譯完成時才會開始匯出。

輪詢的比較 \(英文\)

API 是異步的。 呼叫 exportToFile API 時,它會觸發導出作業。 觸發導出作業之後,請使用 輪詢 來追蹤作業,直到作業完成為止。

匯出完成時,輪詢 API 呼叫會 傳回 Power BI URL 以取得檔案。 URL 可供 24 小時使用。

支援的功能

格式設定

為每個檔案格式指定各種格式設定。 支援的屬性和值相當於 編頁報表 URL 參數的 Device Info 參數

以下提供兩個範例。 第一個是使用報表頁面大小將報表的前四頁導出至 .pptx 檔案。 第二個範例是將報表的第三頁導出至 .jpeg 檔案。

將前四個頁面匯出至 .pptx

{
      "format": "PPTX",
      "paginatedReportConfiguration":{
            "formatSettings":{
                  "UseReportPageSize": "true",
                  "StartPage": "1",
                  "EndPage": "4"
            }
      }
}

將第三頁匯出至 .jpeg

{
      "format": "IMAGE",
      "paginatedReportConfiguration":{
            "formatSettings":{
                  "OutputFormat": "JPEG",
                  "StartPage": "3",
                  "EndPage": "3"
            }
      }
}

報表參數

您可以使用 exportToFile API,以程式設計方式匯出具有一組報表參數的報表。 這是使用 報表參數 功能完成的。

以下是設定報表參數值的範例。

{
      "format": "PDF",
      "paginatedReportConfiguration":{
            "parameterValues":[
                  {"name": "State", "value": "WA"},
                  {"name": "City", "value": "Seattle"},
                  {"name": "City", "value": "Bellevue"},
                  {"name": "City", "value": "Redmond"}
            ]
      }
}

驗證

您可以使用使用者(或主要使用者)或服務 主體進行驗證。

資料欄層級安全性 (RLS)

使用已定義為數據來源的數據列層級安全性 (RLS) 的 Power BI 語意模型時,您可以匯出報表,顯示只有特定使用者可以看到的數據。 例如,如果您要匯出以區域角色定義的銷售報表,您可以以程式設計方式篩選報表,以便只顯示特定區域。

若要使用 RLS 匯出,您必須擁有報表作為數據源使用的 Power BI 語意模型讀取許可權。

以下是提供 RLS 有效用戶名稱的範例。

{
      "format": "PDF",
      "paginatedReportConfiguration":{
            "identities": [
                  {"username": "john@contoso.com"}
            ]
      }
}

單一登入 SQL 和 Dataverse (SSO)

在 Power BI 中,您可以選擇使用 SSO 設定 OAuth。 當您這麼做時,檢視報表的用戶認證會用來擷取數據。 要求標頭中的存取令牌不會用來存取數據。 令牌必須傳入後文中有效的身分識別。

取得您想要存取之資源的正確存取令牌有時可能很棘手。

  • 針對 Azure SQL,資源為 https://database.windows.net
  • 針對 Dataverse,資源是您 https:// 環境的位址。 例如: https://contoso.crm.dynamics.com

使用 AuthenticationContext.AcquireTokenAsync 方法存取令牌 API。

以下是使用存取令牌提供有效身分識別(用戶名稱)的範例。

{
       "format":"PDF",
       "paginatedReportConfiguration":{
          "formatSettings":{
             "AccessiblePDF":"true",
             "PageHeight":"11in",
             "PageWidth":"8.5in",
             "MarginBottom":"2in"
          },
          "identities":[
             {
                "username":"john@contoso.com",
                "identityBlob": {
                "value": "eyJ0eX....full access token"
         }
        }
     ]
   }
}

並行要求數

exportToFile支援有限數目的並行要求。 並行編頁報表轉譯要求的數目上限為 500。 若要避免超過限制並收到太多要求 (429) 錯誤,請分散一段時間或跨容量的負載。

透過 進階版 每位使用者 (PPU)exportToFileAPI 在五分鐘的視窗中只允許一個要求。 在五分鐘的視窗中有多個要求會導致 太多要求 (429) 錯誤。

程式碼範例

您可以在這裡下載程式代碼範例中使用的 Power BI API SDK。

當您建立匯出作業時,有三個步驟要遵循:

  1. 傳送導出要求。
  2. 投票。
  3. 取得檔案。

本節提供每個步驟的範例。

步驟 1 - 傳送匯出要求

第一個步驟是傳送導出要求。 在此範例中,會針對特定頁面範圍、大小和報表參數值傳送匯出要求。

private async Task<string> PostExportRequest(
    Guid reportId,
    Guid groupId)
{
    // For documentation purposes the export configuration is created in this method
    // Ordinarily, it would be created outside and passed in
    var paginatedReportExportConfiguration = new PaginatedReportExportConfiguration()
    {
        FormatSettings = new Dictionary<string, string>()
        {
            {"PageHeight", "14in"},
            {"PageWidth", "8.5in" },
            {"StartPage", "1"},
            {"EndPage", "4"},
        },
        ParameterValues = new List<ParameterValue>()
        {
            { new ParameterValue() {Name = "State", Value = "WA"} },
            { new ParameterValue() {Name = "City", Value = "Redmond"} },
        },
    };

    var exportRequest = new ExportReportRequest
    {
        Format = FileFormat.PDF,
        PaginatedReportExportConfiguration = paginatedReportExportConfiguration,
    };

    var export = await Client.Reports.ExportToFileInGroupAsync(groupId, reportId, exportRequest);

    // Save the export ID, you'll need it for polling and getting the exported file
    return export.Id;
}

步驟 2 - 輪詢

傳送導出要求之後,請使用輪詢來識別您等待的導出檔案何時就緒。

private async Task<Export> PollExportRequest(
    Guid reportId,
    Guid groupId,
    string exportId /* Get from the ExportToAsync response */,
    int timeOutInMinutes,
    CancellationToken token)
{
    Export exportStatus = null;
    DateTime startTime = DateTime.UtcNow;
    const int secToMillisec = 1000;
    do
    {
        if (DateTime.UtcNow.Subtract(startTime).TotalMinutes > timeOutInMinutes || token.IsCancellationRequested)
        {
            // Error handling for timeout and cancellations
            return null;
        }

        var httpMessage = 
            await Client.Reports.GetExportToFileStatusInGroupWithHttpMessagesAsync(groupId, reportId, exportId);
            
        exportStatus = httpMessage.Body;
        if (exportStatus.Status == ExportState.Running || exportStatus.Status == ExportState.NotStarted)
        {
            // The recommended waiting time between polling requests can be found in the RetryAfter header
            // Note that this header is only populated when the status is either Running or NotStarted
            var retryAfter = httpMessage.Response.Headers.RetryAfter;
            var retryAfterInSec = retryAfter.Delta.Value.Seconds;

            await Task.Delay(retryAfterInSec * secToMillisec);
        }
    }
    // While not in a terminal state, keep polling
    while (exportStatus.Status != ExportState.Succeeded && exportStatus.Status != ExportState.Failed);

    return exportStatus;
}

步驟 3 - 取得檔案

輪詢傳回 URL 之後,請使用這個範例來取得收到的檔案。

private async Task<ExportedFile> GetExportedFile(
    Guid reportId,
    Guid groupId,
    Export export /* Get from the GetExportStatusAsync response */)
{
    if (export.Status == ExportState.Succeeded)
    {
        var httpMessage = 
            await Client.Reports.GetFileOfExportToFileInGroupWithHttpMessagesAsync(groupId, reportId, export.Id);

        return new ExportedFile
        {
            FileStream = httpMessage.Body,
            ReportName = export.ReportName,
            FileExtension = export.ResourceFileExtension,
        };
    }

    return null;
}

public class ExportedFile
{
    public Stream FileStream;
    public string ReportName;
    public string FileExtension;
}

端對端範例

這是導出報表的端對端範例。 此範例包含下列階段:

  1. 傳送導出要求
  2. 輪詢。
  3. 取得檔案
private async Task<ExportedFile> ExportPaginatedReport(
    Guid reportId,
    Guid groupId,
    int pollingtimeOutInMinutes,
    CancellationToken token)
{
    try
    {
        var exportId = await PostExportRequest(reportId, groupId);

        var export = await PollExportRequest(reportId, groupId, exportId, pollingtimeOutInMinutes, token);
        if (export == null || export.Status != ExportState.Succeeded)
        {
           // Error, failure in exporting the report
            return null;
        }

        return await GetExportedFile(reportId, groupId, export);
    }
    catch
    {
        // Error handling
        throw;
    }
}

考量與限制

  • 在下列案例中,不支持導出具有 Power BI 語意模型的編頁報表做為其數據來源:

    • 呼叫端是 服務主體配置檔
    • 其中一個語意模型的數據源已設定啟用單一登錄(SSO),並提供有效的身分識別。
    • Power BI 語意模型具有 DirectQuery 至 Azure Analysis Services 或另一個 Power BI 語意模型,並提供有效的身分識別。
  • 在下列情況下,不支援匯出已啟用單一登錄的 Azure Analysis Services 數據源的編頁報表:

  • 若要匯出具有有效身分識別的編頁報表,使用者名稱必須是您租使用者 Microsoft Entra 標識符的現有使用者。

  • 報表的導出限制為60分鐘,這符合使用者存取令牌的存留期。 如果您在匯出大量數據時收到超過 60 分鐘標記的逾時錯誤,請考慮使用適當的篩選來減少數據量。

  • 在在線匯出已發佈的編頁 Power BI 服務 報表時,檔案共用 URL 超連結 (檔案分享 /UNC 路徑) 無法運作。

檢閱如何為您的客戶和組織內嵌內容: