將 Power BI 報表匯出至檔案

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

  • .pptx (PowerPoint)
  • 。Pdf
  • .png
    • 當您匯出至 .png 時,具有多個頁面的報表會壓縮成 .zip 檔案
    • .zip 中的每個檔案都代表報表頁面
    • 頁面名稱與群組 API 中取得頁面 取得頁面的 傳回值相同

注意

進階版每個使用者 (PPU) 不支援使用 exportToFile API 將 Power BI 報表匯出至檔案。

使用範例

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

  • 傳送至列印按鈕 - 在您的應用程式中,建立按一下時觸發匯出作業的按鈕。 作業可以將檢視的報表匯出為 .pdf 或 .pptx。 完成時,使用者可以以下載的形式接收檔案。 您可以使用書簽,以特定狀態匯出報表,包括已設定的篩選、交叉分析篩選器和其他設定。 因為這是非同步 API,所以可能需要一些時間,檔案才能使用。

  • 電子郵件附件 - 使用附加的 .pdf 報表,依設定間隔傳送自動電子郵件。 如果您想要將每週報告自動傳送給主管,此案例會很有用。 如需詳細資訊,請參閱 使用 Power Automate 匯出和傳送 Power BI 報表的電子郵件

使用 API

授權需求

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

管理員設定

使用 API 之前,請確認已啟用下列 系統管理員租使用者設定

  • 將報表匯出為 PowerPoint 簡報或 PDF 檔 - 預設為啟用。
  • 將報表匯出為影像檔 - 僅適用于 .png ,且預設為停用。

「轉譯」事件

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

輪詢的比較 \(英文\)

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

輪詢期間,API 會傳回數位,代表已完成的工作量。 每個匯出作業中的工作都是根據作業中的匯出總數來計算。 匯出包含匯出單一視覺效果,或含有或不含書簽的頁面。 所有匯出都有相同的權數。 例如,如果您的匯出作業包含匯出具有 10 個頁面的報表,而輪詢會傳回 70,表示 API 在匯出作業的 10 個頁面中已處理 7 個。

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

支援的功能

本節說明如何使用下列支援的功能:

選取要列印的頁面

根據 [群組 ] 傳回值中的 [取得頁面 ] 或 [ 取得頁面] 指定您要列印的頁面。 您也可以指定您要匯出的頁面順序。

匯出頁面或單一視覺效果

您可以指定要匯出的頁面或單一視覺效果。 頁面可以透過或不含書簽來匯出。

視匯出類型而定,您必須將不同的屬性傳遞至 ExportReportPage 物件。 下表指定每個匯出作業所需的屬性。

注意

匯出單一視覺效果的權數與匯出頁面相同(包含或不含書簽)。 這表示在系統計算方面,這兩個作業都會有相同的值。

屬性 單一視覺效果 註解
bookmark 選擇性 Does not apply to. 用來匯出處於特定狀態的頁面
pageName Applies to. Applies to. 使用 GetPages REST API 或 getPages 用戶端 API
visualName Does not apply to. Applies to. 有兩種方式可取得視覺效果的名稱:
  • getVisuals 使用用戶端 API
  • 接聽並記錄 visualClicked 事件,此事件會在選取視覺效果時觸發。 如需詳細資訊,請參閱 如何處理事件
  • .

    書籤

    書簽可用來將報表儲存在特定組態中,包括套用的篩選和報表視覺效果的狀態。 您可以使用 exportToFile API,以兩種方式以程式設計方式匯出報表的書簽:

    • 匯出現有的書簽

      若要匯出現有的 報表書簽 ,請使用 name 屬性,這是唯一的(區分大小寫)識別碼,您可以使用書簽 JavaScript API 來取得 該識別碼。

    • 匯出報表的狀態

      若要匯出報表的目前狀態,請使用 state 屬性。 例如,您可以使用書簽的 bookmarksManager.capture 方法來擷取對報表所做的特定使用者所做的變更,然後使用 將其匯出為目前狀態 capturedBookmark.state

    篩選

    reportLevelFilters PowerBIReportExportConfiguration 中使用 ,您可以在篩選準則中匯出報表。

    若要匯出篩選的報表,請將您想要作為篩選 使用的 URL 查詢字串參數 插入 ExportFilter 。 當您輸入字串時,必須移除 ?filter= URL 查詢參數的一部分。

    資料表包含一些您可以傳遞至 ExportFilter 的字串語法範例。

    篩選器 語法 範例
    欄位中的值 資料表/欄位 eq 'value' Store/Territory eq 'NC'
    欄位中的多個值 中的資料表/欄位 ('value1', 'value2') 商店/領土在 ('NC', 'TN')
    一個欄位中的相異值,另一個欄位中有不同的相異值 Table/Field1 eq 'value1' 和 Table/Field2 eq 'value2' Store/Territory eq 'NC' 和 Store/Chain eq 'Fashions Direct'

    驗證

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

    資料列層級安全性 (RLS)

    使用 資料列層級安全性 (RLS) ,您可以匯出報表,其中顯示只有特定使用者可以看到的資料。 例如,如果您要匯出以區域角色定義的銷售報告,您可以以程式設計方式篩選報表,以便只顯示特定區域。

    若要使用 RLS 匯出,您必須具有下列許可權:

    • 寫入並重新共用報表所連線之語意模型的許可權
    • 報表所在工作區的工作區成員或系統管理員

    資料保護

    .pdf 和 .pptx 格式支援 敏感度標籤 。 如果您將具有敏感度標籤的報表匯出至 .pdf 或 .pptx,匯出的檔案就會以其敏感度標籤顯示報表。

    具有敏感度標籤的報表無法使用服務主體 匯出至 .pdf 或 .pptx

    當地語系化

    使用 exportToFile API 時,您可以傳遞所需的地區設定。 當地語系化設定會影響報表的顯示方式,例如,根據選取的本機變更格式設定。

    動態繫結

    若要在報表連接到語意模型時匯出報表,另一個則是預設語意模型,請在呼叫 API 時,在 參數中 datasetToBind 指定必要的資料集識別碼。 深入瞭解動態系結

    並行要求數

    exportToFileAPI 支援有限數目的並行要求。 支援的並行要求數目上限是每個容量 500 個。 若要避免超過限制並收到太多要求 (429) 錯誤,請分散一段時間或跨容量的負載。 只會同時處理報表的五頁。 例如,如果您要匯出含有 50 頁的報表,則會以 10 個循序間隔處理匯出作業。 優化匯出作業時,建議您考慮平行執行幾個作業。

    程式碼範例

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

    1. 傳送匯出要求
    2. 輪詢。
    3. 取得檔案
    4. 使用檔案資料流程

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

    步驟 1 - 傳送匯出要求

    第一個步驟是傳送匯出要求。 在此範例中,會針對特定頁面傳送匯出要求。

    private async Task<string> PostExportRequest(
        Guid reportId,
        Guid groupId,
        FileFormat format,
        IList<string> pageNames = null, /* Get the page names from the GetPages REST API */
        string urlFilter = null)
    {
        var powerBIReportExportConfiguration = new PowerBIReportExportConfiguration
        {
            Settings = new ExportReportSettings
            {
                Locale = "en-us",
            },
            // Note that page names differ from the page display names
            // To get the page names use the GetPages REST API
            Pages = pageNames?.Select(pn => new ExportReportPage(Name = pn)).ToList(),
            // ReportLevelFilters collection needs to be instantiated explicitly
            ReportLevelFilters = !string.IsNullOrEmpty(urlFilter) ? new List<ExportFilter>() { new ExportFilter(urlFilter) } : null,
    
        };
    
        var exportRequest = new ExportReportRequest
        {
            Format = format,
            PowerBIReportConfiguration = powerBIReportExportConfiguration,
        };
    
        // The 'Client' object is an instance of the Power BI .NET SDK
        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<HttpOperationResponse<Export>> PollExportRequest(
        Guid reportId,
        Guid groupId,
        string exportId /* Get from the PostExportRequest response */,
        int timeOutInMinutes,
        CancellationToken token)
    {
        HttpOperationResponse<Export> httpMessage = null;
        Export exportStatus = null;
        DateTime startTime = DateTime.UtcNow;
        const int c_secToMillisec = 1000;
        do
        {
            if (DateTime.UtcNow.Subtract(startTime).TotalMinutes > timeOutInMinutes || token.IsCancellationRequested)
            {
                // Error handling for timeout and cancellations 
                return null;
            }
    
            // The 'Client' object is an instance of the Power BI .NET SDK
            httpMessage = await Client.Reports.GetExportToFileStatusInGroupWithHttpMessagesAsync(groupId, reportId, exportId);
            exportStatus = httpMessage.Body;
    
            // You can track the export progress using the PercentComplete that's part of the response
            SomeTextBox.Text = string.Format("{0} (Percent Complete : {1}%)", exportStatus.Status.ToString(), exportStatus.PercentComplete);
            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 not always populated
                var retryAfter = httpMessage.Response.Headers.RetryAfter;
                var retryAfterInSec = retryAfter.Delta.Value.Seconds;
                await Task.Delay(retryAfterInSec * c_secToMillisec);
            }
        }
        // While not in a terminal state, keep polling
        while (exportStatus.Status != ExportState.Succeeded && exportStatus.Status != ExportState.Failed);
    
        return httpMessage;
    }
    

    步驟 3 - 取得檔案

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

    private async Task<ExportedFile> GetExportedFile(
        Guid reportId,
        Guid groupId,
        Export export /* Get from the PollExportRequest response */)
    {
        if (export.Status == ExportState.Succeeded)
        {
            // The 'Client' object is an instance of the Power BI .NET SDK
            var fileStream = await Client.Reports.GetFileOfExportToFileAsync(groupId, reportId, export.Id);
            return new ExportedFile
            {
                FileStream = fileStream,
                FileSuffix = export.ResourceFileExtension,
            };
        }
        return null;
    }
    
    public class ExportedFile
    {
        public Stream FileStream;
        public string FileSuffix;
    }
    

    步驟 4 - 使用檔案資料流程

    當您有檔案資料流程時,您可以以最符合您需求的方式處理它。 例如,您可以傳送電子郵件給它,或使用它來下載匯出的報表。

    端對端範例

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

    1. 傳送匯出要求
    2. 輪詢。
    3. 取得檔案
    private async Task<ExportedFile> ExportPowerBIReport(
    	Guid reportId,
    	Guid groupId,
    	FileFormat format,
    	int pollingtimeOutInMinutes,
    	CancellationToken token,
    	IList<string> pageNames = null,  /* Get the page names from the GetPages REST API */
        string urlFilter = null)
    {
    	const int c_maxNumberOfRetries = 3; /* Can be set to any desired number */
    	const int c_secToMillisec = 1000;
    	try
    	{
    		Export export = null;
    		int retryAttempt = 1;
    		do
    		{
    			var exportId = await PostExportRequest(reportId, groupId, format, pageNames, urlFilter);
    			var httpMessage = await PollExportRequest(reportId, groupId, exportId, pollingtimeOutInMinutes, token);
    			export = httpMessage.Body;
    			if (export == null)
    			{
    				// Error, failure in exporting the report
    				return null;
    			}
    			if (export.Status == ExportState.Failed)
    			{
    				// Some failure cases indicate that the system is currently busy. The entire export operation can be retried after a certain delay
    				// In such cases the recommended waiting time before retrying the entire export operation can be found in the RetryAfter header
    				var retryAfter = httpMessage.Response.Headers.RetryAfter;
    				if(retryAfter == null)
    				{
    				    // Failed state with no RetryAfter header indicates that the export failed permanently
    				    return null;
                    }
    
                    var retryAfterInSec = retryAfter.Delta.Value.Seconds;
                    await Task.Delay(retryAfterInSec * c_secToMillisec);
                }
            }
            while (export.Status != ExportState.Succeeded && retryAttempt++ < c_maxNumberOfRetries);
    
            if (export.Status != ExportState.Succeeded)
            {
                // Error, failure in exporting the report
                return null;
            }
    
            var exportedFile = await GetExportedFile(reportId, groupId, export);
    
            // Now you have the exported file stream ready to be used according to your specific needs
            // For example, saving the file can be done as follows:
            /*
                var pathOnDisk = @"C:\temp\" + export.ReportName + exportedFile.FileSuffix;
    
                using (var fileStream = File.Create(pathOnDisk))
                {
                    exportedFile.FileStream.CopyTo(fileStream);
                }
            */
    
            return exportedFile;
        }
        catch
        {
            // Error handling
            throw;
        }
    }
    

    考量與限制

    • 匯出 API 作業負載會評估為緩慢執行的背景作業,如進階版容量負載評估 中所述
    • 您要匯出之報表中的所有相關語意模型必須位於進階版或內嵌容量上,包括具有直接查詢連線的語意模型。
    • 匯出的報表不能超過 250 MB 的檔案大小。
    • 匯出至 .png 時,不支援敏感度標籤。
    • 可以包含在單一匯出報表中的匯出 (單一視覺效果或報表頁面) 數目為 50 (不包括匯出編頁報表)。 如果要求包含更多匯出,API 會傳回錯誤並取消匯出作業。
    • Power BI 報表匯出至檔案不支援個人書簽 永續性篩選
    • 如果不使用書簽或 reportLevelFilters,API 會 exportToFile 匯出具有預設值的報表。
    • 不支援此處所列的 Power BI 視覺效果。 當您匯出包含這些視覺效果的報表時,包含這些視覺效果的報表部分不會轉譯,並顯示錯誤符號。
      • 未認證的 Power BI 自訂視覺效果
      • R 視覺效果
      • PowerApps
      • Python 視覺效果
      • Power Automate
      • 編頁報表視覺效果
      • Visio
      • ArcGIS 視覺效果

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

    其他問題嗎? 嘗試Power BI 社群