教程:为组织将 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
    应用程序 IDApplication ID
    工作区 IDWorkspace ID
    报表 IDReport ID
    AADAuthorityUrlAADAuthorityUrl

    Cloud.config 文件

应用程序 IDApplication ID

将 Azure 中的“应用 ID” 填入“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 的“应用程序 ID” 。There's an Application ID that is listed as a GUID. 使用此“应用 ID” 作为应用的“applicationId” 。Use this Application ID as the applicationId for the application.

    applicationId

工作区 IDWorkspace ID

使用 Power BI 中的“应用工作区(组) GUID”填写“workspaceId”信息 。Fill in the workspaceId information with the app workspace (group) GUID from Power BI. 登录 Power BI 服务或使用 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

报表 IDReport ID

使用 Power BI 中的“报表 GUID”填写“reportId”信息 。Fill in the reportId information with the report GUID from Power BI. 登录 Power BI 服务或使用 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 (用报表所有者的租户 ID 替换 report-owner-tenant-id) 。For 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. 有关详细信息,请参阅对用户进行身份验证并获取 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. 在报表列表中,可以获取报表 ID。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 调用,必须添加格式为“持有者 {访问令牌}” 的授权 标头。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.cs 文件中提供了加载要嵌入内容项的示例 。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 vCore 总数Total vCores
(后端 + 前端)(back end + front end)
后端 vCoreBack-end vCores 前端 vCoreFront-end vCores DirectQuery/实时连接限制DirectQuery/live connection limits
EM1EM1 1 个 vCore1 vCore 0.5 个 vCore,10 GB RAM0.5 vCore, 10 GB of RAM 0.5 个 vCore0.5 vCore 每秒 3.753.75 per second
EM2EM2 2 个 vCore2 vCores 1 个 vCore,10 GB RAM1 vCore, 10 GB of RAM 1 个 vCore1 vCores 每秒 7.57.5 per second
EM3EM3 4 个 vCore4 vCores 2 个 vCore,10 GB RAM2 vCores, 10 GB of RAM 2 个 vCore2 vCores 每秒 15 个15 per second
P1P1 8 个 vCore8 vCores 4 个 vCore,25 GB RAM4 vCores, 25 GB of RAM 4 个 vCore4 vCores 每秒 30 个30 per second
P2P2 16 个 vCore16 vCores 8 个 vCore,50 GB RAM8 vCores, 50 GB of RAM 8 个 vCore8 vCores 每秒 60 个60 per second
P3P3 32 个 vCore32 vCores 16 个 vCore,100 GB RAM16 vCores, 100 GB of RAM 16 个 vCore16 vCores 每秒 120 个120 per second
P4P4 64 个 vCore64 vCores 32 个 vCore,200 GB RAM32 vCores, 200 GB of RAM 32 个 vCore32 vCores 每秒 240 个240 per second
P5P5 128 个 vCore128 vCores 64 vCore,400 GB RAM64 vCores, 400 GB of RAM 64 个 vCore64 vCores 每秒 480 个480 per second

备注

  • 当你尝试嵌入到 Microsoft Office 应用时,可以使用 EM SKU 访问具有免费 Power BI 许可证的内容。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.