分享方式:


將 Power BI 報表匯出至檔案

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

  • .pptx (PowerPoint)
  • .pdf
  • .png
    • 多頁報表在匯出為 .png 時會壓縮成 .zip 檔案
    • .zip 中的每個檔案都代表一張報表頁面
    • 頁面名稱與取得頁面 \(英文\) 或取得群組中的頁面 \(英文\) API 的傳回值相同

注意

Premium Per User (PPU) 不支援使用 exportToFile API,將 Power BI 報表匯出至檔案。

使用範例

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

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

  • 電子郵件附件 - 以設定的間隔傳送自動電子郵件,並附加 .pdf 報表。 若要將每週報表自動傳送給主管,這個案例就很有用。 如需詳細資訊,請參閱使用 Power Automate 匯出 Power BI 報表並以電子郵件傳送

使用 API

授權需求

  • 您匯出的報表必須位於 Premium、Embedded 或 Fabric 容量支援的工作區中。
  • Premium Per User (PPU) 支援 exportToFile API。

管理員設定

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

  • 將報表匯出成 PowerPoint 簡報或 PDF 文件 - 預設為啟用。
  • 將報表匯出為影像檔 - 只有 .png 才需要,預設停用。

「轉譯」事件

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

輪詢的比較 \(英文\)

該 API 是非同步的。 呼叫 exportToFile \(英文\) API 時,其會觸發匯出作業。 觸發匯出作業之後,請使用輪詢 \(英文\) 來追蹤作業,直到完成為止。

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

當匯出完成時,輪詢 API 呼叫會傳回 Power BI URL \(英文\) 來取得檔案。 該 URL 在 24 小時內可供使用。

支援的功能

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

選取要列印的頁面

根據取得頁面 \(英文\) 或取得群組中的頁面 \(英文\) 傳回值,指定您要列印的頁面。 您也可以指定您要匯出的頁面順序。

匯出頁面或單一視覺效果

您可以指定要匯出的頁面或單一視覺效果。 頁面匯出時可以包含或不含書籤。

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

注意

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

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

    書籤

    書籤可用來以特定設定儲存報表,包括已套用的篩選條件與報表視覺效果的狀態。 您可以透過兩種方式,使用 exportToFile \(英文\) API,以程式設計方式匯出報表的書籤:

    • 匯出現有的書籤

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

    • 匯出報表的狀態

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

    注意

    不支援個人書籤永續性篩選 \(英文\)。

    篩選

    PowerBIReportExportConfiguration 中使用 reportLevelFilters,您可以利用篩選的條件來匯出報表。

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

    此表包含數個您可以傳遞給 ExportFilter 之字串的語法範例。

    篩選器 語法 範例
    一個欄位中的一個值 Table/Field eq 'value' Store/Territory eq 'NC'
    一個欄位中的多個值 Table/Field in ('value1', 'value2') Store/Territory in ('NC', 'TN')
    一個欄位中的相異值,且另一個欄位中有不同的相異值 Table/Field1 eq 'value1' and Table/Field2 eq 'value2' Store/Territory eq 'NC' and Store/Chain eq 'Fashions Direct'

    驗證

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

    資料列層級安全性 (RLS)

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

    若要使用 RLS 匯出,您也必須有下列權限:

    • 報表所連接之語意模型的寫入和再次共用權限
    • 報表所在工作區的工作區成員或管理員

    資料保護

    .pdf 和 .pptx 格式支援敏感度標籤。 如果將具有敏感度標籤的報表匯出為 .pdf 或 .pptx,則所匯出檔案會顯示有敏感度標籤的報表。

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

    當地語系化

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

    動態繫結

    若要在報表連接到預設語意模型以外的語意模型時匯出報表,請在呼叫 API 時,在 datasetToBind 參數中指定必要的資料集識別碼。 深入了解動態繫結

    並行要求數

    exportToFile API 支援的並行要求數目有限。 支援的並行要求數目上限是每個容量 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;
        }
    }
    

    考量與限制

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

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

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