教學課程:為組織將 Power BI 內容內嵌至應用程式Tutorial: Embed Power BI content into an application for your organization

Power BI 中,您可以利用使用者擁有資料,將報表 (Power BI 或編頁報表)、儀表板或磚內嵌至應用程式。In Power BI, you can embed reports (Power BI or Paginated), dashboards, or tiles into an application by using user owns data. 使用者擁有資料可讓應用程式延伸 Power BI 服務,使其可用內嵌式分析。User owns data lets your application extend the Power BI service so it can use embedded analytics. 本教學課程會示範如何將報表 (Power BI 或編頁報表) 整合至應用程式。This tutorial demonstrates how to integrate a report (Power BI or Paginated) into an application. 您可以使用 Power BI .NET SDK 搭配 Power BI JavaScript API,為組織將 Power BI 內嵌到應用程式中。You use the Power BI .NET SDK with the Power BI JavaScript API to embed Power BI into an application for your organization.

Power BI 內嵌報表

在本教學課程中,您會學習下列工作:In this tutorial, you learn the following tasks:

  • 在 Azure 中註冊應用程式。Register an application in Azure.
  • 使用您的 Power BI 租用戶將 Power BI 或編頁報表內嵌到應用程式。Embed a Power BI or Paginated report into an application using your Power BI tenant.

先決條件Prerequisites

若要開始,您必須具備:To get started, you're required to have:

如果您尚未註冊 Power BI Pro,請先註冊免費試用,再開始進行。If you're not signed up for Power BI Pro, sign up for a free trial before you begin.

如果您沒有 Azure 訂用帳戶,請先建立免費帳戶,再開始進行。If you don’t have an Azure subscription, create a free account before you begin.

設定您的內嵌分析開發環境Set up your embedded analytics development environment

在您開始將報表、儀表板或磚內嵌至您的應用程式之前,必須先確定您的環境允許使用 Power BI 內嵌。Before you start embedding reports, dashboard, or tiles into your application, you need to make sure your environment allows for embedding with Power BI.

您可以瀏覽內嵌設定工具,即可快速開始使用及下載範例應用程式,協助您逐步建立環境及內嵌報表。You can go through the Embedding setup tool, so you can quickly get started and download a sample application that helps you walk through creating an environment and embedding a report. 在內嵌編頁報表的案例中,您需要指派至少 P1 容量給所建立的應用程式工作區。In the case of embedding a paginated report you need to assign at least a P1 capacity to the created app workspace.

若選擇手動設定環境,您可以繼續進行下列步驟。If you choose to set up the environment manually, you can continue below.

在 Azure Active Directory 中註冊應用程式Register an application in Azure Active Directory

請向 Azure Active Directory 註冊您的應用程式,以允許該應用程式存取 Power BI REST APIRegister your application with Azure Active Directory to allow your application access to the Power BI REST APIs. 註冊您的應用程式可讓您為應用程式建立身分識別,並指定對 Power BI REST 資源的權限。Registering your application allows you to establish an identity for your application and specify permissions to Power BI REST resources.

您必須繼續註冊伺服器端 Web 應用程式應用程式。You need to proceed with registering a server-side web application app. 您註冊伺服器端 Web 應用程式,以建立應用程式祕密。You register a server-side web application to create an application secret.

設定您的 Power BI 環境Set up your Power BI environment

建立應用程式工作區Create an app workspace

如果您要為客戶內嵌報表、儀表板或磚,就必須將您的內容放在應用程式工作區內。If you're embedding reports, dashboards, or tiles for your customers, then you have to place your content within an app workspace. 有不同類型的工作區可供您設定:傳統工作區新工作區There are different types of workspaces that you can set up: the traditional workspaces or the new workspaces.

建立並發佈您的 Power BI 報表Create and publish your Power BI reports

您可以使用 Power BI Desktop 來建立您的報表和資料集。You can create your reports and datasets by using Power BI Desktop. 然後您可以將那些報表發佈到應用程式工作區。Then you can publish those reports to an app workspace. 發佈報表的終端使用者必須有 Power BI Pro 授權,才能發佈至應用程式工作區。The end user publishing the reports needs to have a Power BI Pro license to publish to an app workspace.

  1. 從 GitHub 下載範例示範Download the sample Demo from GitHub.

    下載示範

  2. 在 Power BI Desktop 中開啟範例 .pbix 報表。Open the sample .pbix report in Power BI Desktop.

    範例 Power BI Desktop 報表

  3. 發佈至應用程式工作區。Publish to the app workspace.

    發佈 Power BI Desktop 報表

    現在,您可在線上 Power BI 服務中檢視該報表。Now you can view the report in the Power BI service online.

    檢視 Power BI Desktop 報表

建立並發佈您的編頁報表Create and publish your paginated reports

您可以使用 Power BI 報表產生器來建立編頁報表。You can create your paginated reports by using Power BI Report Builder. 然後,您可以上傳報表到至少指派 P1 容量的應用程式工作區。Then you can upload the report to an app workspace assigned to at least a P1 capacity. 上傳報表的終端使用者需要擁有 Power BI Pro 授權才能發佈至應用程式工作區。The end-user uploading the report must have a Power BI Pro license to publish to an app workspace.

使用範例應用程式來內嵌內容Embed your content by using the sample application

此範例刻意保持簡單以供示範之用。This sample is deliberately kept simple for demonstration purposes.

請遵循下列步驟,使用範例應用程式開始內嵌您的內容。Follow the steps below to start embedding your content using the sample application.

  1. 下載 Visual Studio (版本 2013 或更新版本)。Download Visual Studio (version 2013 or later). 務必下載最新 NuGet 套件Make sure to download the latest NuGet package.

  2. 從 GitHub 下載使用者擁有資料範例以開始使用。Download the User Owns Data sample from GitHub to get started.

    使用者擁有資料應用程式範例

  3. 開啟範例應用程式中的 Cloud.config 檔案。Open the Cloud.config file in the sample application.

    您需要填寫幾個欄位,才能執行應用程式。There are fields you need to fill in to run the application.

    欄位Field
    應用程式識別碼Application ID
    工作區識別碼Workspace ID
    報表識別碼Report ID
    AADAuthorityUrlAADAuthorityUrl

    Cloud.config 檔案

應用程式識別碼Application ID

使用從 Azure 取得的應用程式識別碼填入 applicationId 資訊。Fill in the applicationId information with the Application ID from Azure. 應用程式會使用 applicationId 來向您要求權限的使用者表明其身分。The applicationId is used by the application to identify itself to the users from which you're requesting permissions.

若要取得 applicationId,請遵循下列步驟:To get the applicationId, follow these steps:

  1. 登入Azure 入口網站Sign into the Azure portal.

  2. 在左側的功能窗格中,選取 [所有服務] 及 [應用程式註冊] 。In the left-hand navigation pane, select All Services, and select App Registrations.

  3. 選取需要 applicationId 的應用程式。Select the application that needs the applicationId.

    選擇應用程式

  4. 有一個以 GUID 形式列出的「應用程式識別碼」 。There's an Application ID that is listed as a GUID. 請使用此應用程式識別碼作為應用程式的 applicationIdUse this Application ID as the applicationId for the application.

    applicationId

工作區識別碼Workspace ID

workspaceId 資訊中,填入來自 Power BI 的應用程式工作區 (群組) GUID。Fill in the workspaceId information with the app workspace (group) GUID from Power BI. 您可以在登入 Power BI 服務時從 URL,或使用 Powershell 取得這項資訊。You can get this information either from the URL when signed into the Power BI service or using Powershell.

URLURL

workspaceId

PowershellPowershell

Get-PowerBIworkspace -name "User Owns Embed Test"

來自 powershell 的 workspaceId

報表識別碼Report ID

reportId 資訊中,填入來自 Power BI 的報表 GUID。Fill in the reportId information with the report GUID from Power BI. 您可以在登入 Power BI 服務時從 URL,或使用 Powershell 取得這項資訊。You can get this information either from the URL when signed into the Power BI service or using Powershell.

Power BI 報表 URLPower BI Report URL

PBI reportId

編頁報表 URLPaginated Report URL

編頁 reportId

PowershellPowershell

Get-PowerBIworkspace -name "User Owns Embed Test" | Get-PowerBIReport

來自 powershell 的 reportId

AADAuthorityUrlAADAuthorityUrl

利用使您可在組織租用戶中內嵌,或以來賓使用者身分內嵌的 URL,填滿 AADAuthorityUrl 資訊。Fill in the AADAuthorityUrl information with the URL that either allows you to embed within your organizational tenant or embed with a guest user.

若要以您的組織租用戶內嵌,請使用 URL - https://login.microsoftonline.com/common/oauth2/authorizeFor embedding with your organizational tenant, use the URL - https://login.microsoftonline.com/common/oauth2/authorize.

若要以來賓內嵌,請使用 URL - https://login.microsoftonline.com/report-owner-tenant-id - 您可在其中新增報表擁有者的租用戶識別碼,以取代 report-owner-tenant-idFor embedding with a guest, use the URL - https://login.microsoftonline.com/report-owner-tenant-id - where you add the tenant ID of the report owner in replacement of report-owner-tenant-id.

執行應用程式Run the application

  1. Visual Studio 中選取 [執行] 。Select Run in Visual Studio.

    執行應用程式

  2. 接著,選取 [內嵌報表] 。Then select Embed Report. 視您選擇要進行測試之內容的不同 (報表、儀表板或磚),接著在應用程式中選取該選項。Depending on which content you choose to test with - reports, dashboards or tiles - then select that option in the application.

    選取內容

  3. 現在,您已可以在範例應用程式中檢視該報表。Now you can view the report in the sample application.

    在應用程式中檢視報表

在應用程式中內嵌內容Embed your content within your application

雖然使用 Power BI REST API 可以完成內嵌您內容的步驟,本文描述的範例程式碼仍是使用 .NET SDK 撰寫。Even though the steps to embed your content can be done with the Power BI REST APIs, the example codes described in this article are made with the .NET SDK.

若要將報表整合至 Web 應用程式,您需要使用 Power BI REST API 或 Power BI C# SDK。To integrate a report into a web app, you use the Power BI REST API or the Power BI C# SDK. 您也可以使用 Azure Active Directory 授權存取權杖來取得報表。You also use an Azure Active Directory authorization access token to get a report. 然後,您可以使用相同的存取權杖來載入報表。Then you load the report by using the same access token. Power BI Rest API 可讓您以程式設計方式存取特定的 Power BI 資源。The Power BI Rest API provides programmatic access to specific Power BI resources. 如需詳細資訊,請參閱 Power BI REST APIPower BI JavaScript APIFor more information, see Power BI REST APIs and the Power BI JavaScript API.

從 Azure AD 取得存取權杖Get an access token from Azure AD

在您的應用程式中,您必須從 Azure AD 取得存取權杖,才能呼叫 Power BI REST API。Within your application, you must get an access token from Azure AD before you can make calls to the Power BI REST API. 如需詳細資訊,請參閱 Authenticate users and get an Azure AD access token for your Power BI app (驗證使用者,並為 Power BI 應用程式取得 Azure AD 存取權杖)。For more information, see Authenticate users and get an Azure AD access token for your Power BI app.

取得報表Get a report

若要取得 Power BI 或編頁報表,請使用取得報表作業來取得 Power BI 報表和編頁報表清單。To get a Power BI or paginated report, you use the Get Reports operation, which gets a list of Power BI and paginated reports. 您可以從報表清單中取得報表識別碼。From the list of reports, you can get a report ID.

使用存取權杖取得報表Get reports by using an access token

取得報表作業會傳回報表清單。The Get Reports operation returns a list of reports. 您可以從報表清單中取得單一報表。You can get a single report from the list of reports.

若要進行 REST API 呼叫,您必須使用 Bearer {access token} 的格式包含 Authorization 標頭。To make the REST API call, you must include an Authorization header in the format of Bearer {access token}.

利用 REST API 取得報表Get reports with the REST API

以下程式碼範例示範如何使用 REST API 擷取報表:The following code sample shows you how to retrieve reports with the REST API:

注意

範例應用程式中的 Default.aspx.cs 檔案中有提供範例,其中示範了如何取得您要內嵌的內容項目。A sample of getting a content item that you want to embed is available in the Default.aspx.cs file in the sample application. 範例包括報表、儀表板或磚。Examples are a report, dashboard, or tile.

using Newtonsoft.Json;

//Get a Report. In this sample, you get the first Report.
protected void GetReport(int index)
{
    //Configure Reports request
    System.Net.WebRequest request = System.Net.WebRequest.Create(
        String.Format("{0}/Reports",
        baseUri)) as System.Net.HttpWebRequest;

    request.Method = "GET";
    request.ContentLength = 0;
    request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken.Value));

    //Get Reports response from request.GetResponse()
    using (var response = request.GetResponse() as System.Net.HttpWebResponse)
    {
        //Get reader from response stream
        using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
        {
            //Deserialize JSON string
            PBIReports Reports = JsonConvert.DeserializeObject<PBIReports>(reader.ReadToEnd());

            //Sample assumes at least one Report.
            //You could write an app that lists all Reports
            if (Reports.value.Length > 0)
            {
                var report = Reports.value[index];

                txtEmbedUrl.Text = report.embedUrl;
                txtReportId.Text = report.id;
                txtReportName.Text = report.name;
            }
        }
    }
}

//Power BI Reports used to deserialize the Get Reports response.
public class PBIReports
{
    public PBIReport[] value { get; set; }
}
public class PBIReport
{
    public string id { get; set; }
    public string reportType { get; set }
    public string name { get; set; }
    public string webUrl { get; set; }
    public string embedUrl { get; set; }
}

使用 .NET SDK 取得報表Get reports by using the .NET SDK

您可以使用 .NET SDK 擷取報表清單,而不必直接呼叫 REST API。You can use the .NET SDK to retrieve a list of reports instead of calling the REST API directly. 下列程式碼範例會示範如何列出報表:The following code sample shows you how to list reports:

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

var tokenCredentials = new TokenCredentials(<ACCESS TOKEN>, "Bearer");

// Create a Power BI Client object. It is used to call Power BI APIs.
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
{
    // Get the first report all reports in that workspace
    ODataResponseListReport reports = client.Reports.GetReports();

    Report report = reports.Value.FirstOrDefault();

    var embedUrl = report.EmbedUrl;
}

使用 JavaScript 載入報表Load a report by using JavaScript

您可以使用 JavaScript 將報表載入網頁上的 div 元素中。You can use JavaScript to load a report into a div element on your web page. 下列程式碼範例示範如何從指定工作區擷取報表:The following code sample shows you how to retrieve a report from a given workspace:

注意

範例應用程式Default.aspx 檔案中具有範例,可讓您載入要內嵌的內容項目。A sample of loading a content item that you want to embed is available in the Default.aspx file in the sample application.

<!-- Embed Report-->
<div> 
    <asp:Panel ID="PanelEmbed" runat="server" Visible="true">
        <div>
            <div><b class="step">Step 3</b>: Embed a report</div>

            <div>Enter an embed url for a report from Step 2 (starts with https://):</div>
            <input type="text" id="tb_EmbedURL" style="width: 1024px;" />
            <br />
            <input type="button" id="bEmbedReportAction" value="Embed Report" />
        </div>

        <div id="reportContainer"></div>
    </asp:Panel>
</div>

Site.masterSite.master

window.onload = function () {
    // client side click to embed a selected report.
    var el = document.getElementById("bEmbedReportAction");
    if (el.addEventListener) {
        el.addEventListener("click", updateEmbedReport, false);
    } else {
        el.attachEvent('onclick', updateEmbedReport);
    }

    // handle server side post backs, optimize for reload scenarios
    // show embedded report if all fields were filled in.
    var accessTokenElement = document.getElementById('MainContent_accessTokenTextbox');
    if (accessTokenElement !== null) {
        var accessToken = accessTokenElement.value;
        if (accessToken !== "")
            updateEmbedReport();
    }
};

// update embed report
function updateEmbedReport() {

    // check if the embed url was selected
    var embedUrl = document.getElementById('tb_EmbedURL').value;
    if (embedUrl === "")
        return;

    // get the access token.
    accessToken = document.getElementById('MainContent_accessTokenTextbox').value;

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'report',
        accessToken: accessToken,
        embedUrl: embedUrl
    };

    // Grab the reference to the div HTML element that will host the report.
    var reportContainer = document.getElementById('reportContainer');

    // Embed the report and display it within the div container.
    var report = powerbi.embed(reportContainer, config);

    // report.on will add an event handler which prints to Log window.
    report.on("error", function (event) {
        var logView = document.getElementById('logView');
        logView.innerHTML = logView.innerHTML + "Error<br/>";
        logView.innerHTML = logView.innerHTML + JSON.stringify(event.detail, null, "  ") + "<br/>";
        logView.innerHTML = logView.innerHTML + "---------<br/>";
    }
  );
}

使用 Power BI Premium 專用容量Using a Power BI Premium dedicated capacity

現在您已完成應用程式的開發,就可以為您的應用程式工作區配置專用容量。Now that you've completed developing your application, it's time to back your app workspace with a dedicated capacity.

建立專用容量Create a dedicated capacity

建立專用容量,您應用程式工作區中的內容即可享有專用資源。By creating a dedicated capacity, you can take advantage of having a dedicated resource for the content in your app workspace. 針對編頁報表,您必須使用至少 P1 容量來備份您的應用程式工作區。For paginated reports you must back your app workspace with at least a P1 capacity. 您可以使用 Power BI Premium 建立專用容量。You can create a dedicated capacity by using Power BI Premium.

下表列出 Microsoft Office 365 中可用的 Power BI Premium SKU:The following table lists the Power BI Premium SKUs available in Microsoft Office 365:

容量節點Capacity node V 核心總數Total vCores
(後端 + 前端)(back end + front end)
後端 V 核心數Back-end vCores 前端 V 核心數Front-end vCores DirectQuery/即時連線限制DirectQuery/live connection limits
EM1EM1 1 個 V 核心1 vCore 0.5 個 V 核心,10 GB RAM0.5 vCore, 10 GB of RAM 0.5 個 V 核心0.5 vCore 每秒 3.75 個3.75 per second
EM2EM2 2 個 V 核心2 vCores 1 個 V 核心,10 GB RAM1 vCore, 10 GB of RAM 1 個 V 核心1 vCores 每秒 7.5 個7.5 per second
EM3EM3 4 個 V 核心4 vCores 2 個 V 核心,10 GB RAM2 vCores, 10 GB of RAM 2 個 V 核心2 vCores 每秒 15 個15 per second
P1P1 8 個 V 核心8 vCores 4 個 V 核心,25 GB RAM4 vCores, 25 GB of RAM 4 個 V 核心4 vCores 每秒 30 個30 per second
P2P2 16 個 V 核心16 vCores 8 個 V 核心,50 GB RAM8 vCores, 50 GB of RAM 8 個 V 核心8 vCores 每秒 60 個60 per second
P3P3 32 個 V 核心32 vCores 16 個 V 核心,100 GB RAM16 vCores, 100 GB of RAM 16 個 V 核心16 vCores 每秒 120 個120 per second
P4P4 64 個 V 核心64 vCores 32 個 V 核心,200 GB RAM32 vCores, 200 GB of RAM 32 個 V 核心32 vCores 每秒 240 個240 per second
P5P5 128 個 V 核心128 vCores 64 個 V 核心,400 GB RAM64 vCores, 400 GB of RAM 64 個 V 核心64 vCores 每秒 480 個480 per second

注意

  • 當您嘗試使用 Microsoft Office 應用程式進行內嵌時,您可以搭配免費的 Power BI 授權,使用 EM SKU 來存取內容。When you’re trying to embed with Microsoft Office apps, you can use EM SKUs to access content with a free Power BI license. 但是,您無法在使用 Powerbi.com 或 Power BI 行動版時,搭配免費的 Power BI 授權來存取內容。But you can't access content with a free Power BI license when you're using Powerbi.com or Power BI mobile.
  • 當您嘗試透過利用 Powerbi.com 或 Power BI 行動版,使用 Microsoft Office 應用程式來進行內嵌時,您可以使用免費 Power BI 授權來存取內容。When you're trying to embed with Microsoft Office apps by using Powerbi.com or Power BI mobile, you can access content with a free Power BI license.

將應用程式工作區指派至專用容量Assign an app workspace to a dedicated capacity

建立專用容量之後,您可以將應用程式工作區指派到該專用容量。After you create a dedicated capacity, you can assign your app workspace to that dedicated capacity. 若要完成此處理序,請遵循下列步驟:To complete this process, follow these steps:

  1. 在 Power BI 服務中,展開工作區,然後選取用於內嵌內容工作區的省略符號。Within the Power BI service, expand workspaces and select the ellipsis for the workspace you're using for embedding your content. 然後選取 [編輯工作區] 。Then select Edit workspaces.

    編輯工作區

  2. 展開 [進階] ,然後啟用 [專用容量] 。Expand Advanced and enable Dedicated capacity. 選取您建立的專用容量。Select the dedicated capacity you created. 接著,選取 [儲存] 。Then select Save.

    指派專用容量

  3. 在您選取 [儲存] 後,應該會在應用程式工作區名稱的旁邊看到一個鑽石。After you select Save, you should see a diamond next to the app workspace name.

    繫結至容量的應用程式工作區

管理員設定Admin settings

全域管理員或 Power BI 服務系統管理員可以為租用戶開啟或關閉使用 REST API 的能力。Global admins or Power BI service administrators can turn the ability to use the REST APIs on or off for a tenant. Power BI 系統管理員可以為整個組織或個別安全性群組進行此設定。Power BI admins can set this setting for the entire organization or for individual security groups. 根據預設,會為整個組織啟用這個設定。It's enabled for the entire organization by default. 您可以在 Power BI 系統管理入口網站進行這些變更。You can make these changes in the Power BI admin portal.

後續步驟Next steps

在本教學課程中,您已了解如何使用 Power BI 組織帳戶將 Power BI 內容內嵌至應用程式。In this tutorial, you learned how to embed Power BI content into an application by using your Power BI organization account. 您現在可以嘗試使用應用程式將 Power BI 內容內嵌至應用程式。You can now try to embed Power BI content into an application by using apps. 您也可以嘗試為您的客戶內嵌 Power BI 內容 (目前尚未支援內嵌編頁報表):You can also try to embed Power BI content for your customers (not supported yet for embedding paginated reports):

如果您有更多問題,請嘗試詢問 Power BI 社群If you have more questions, try asking the Power BI Community.