将 Power BI 仪表板、磁贴或报表嵌入应用中Embed a Power BI dashboard, tile, or report into your application

了解如何在为客户嵌入内容时,通过调用 Power BI .Net SDK 和 Power BI JavaScript API,将仪表板、磁贴或报表集成到或嵌入 Web 应用中。Learn how to integrate, or embed, a dashboard, tile or report, into a web app using the Power BI .NET SDK along with the Power BI JavaScript API when embedding for your customers. 这通常是 ISV 方案。This is typically the ISV scenario.

嵌入的仪表板

若要开始按照此演练操作,需要有 Power BI Pro 帐户。To get started with this walkthrough, you need a Power BI Pro account. 如果没有帐户,可以依次注册免费 Power BI 帐户Power BI Pro 试用版,也可以创建自己的 Azure Active Directory 租户用于测试。If you don't have an account, you can sign up for a free Power BI account and then sign up for a Power BI Pro trial, or you can create your own Azure Active Directory tenant for testing purposes.

备注

要改为为组织嵌入仪表板?Looking to embed a dashboard for your organization instead? 请参阅为组织将仪表板集成到应用中See, Integrate a dashboard into an app for your organization.

若要将仪表板集成到 Web 应用,请使用 Power BI API 和 Azure Active Directory (AD) 授权访问令牌来获取仪表板。To integrate a dashboard into a web app, you use the Power BI API, and an Azure Active Directory (AD) authorization access token to get a dashboard. 然后,使用嵌入令牌加载仪表板。Then, you load the dashboard using an embed token. Power BI API 向某些 Power BI 资源提供了编程访问权限。The Power BI API provides programmatic access to certain Power BI resources. 有关详细信息,请参阅 Power BI REST API 概述Power BI .NET SDKPower BI JavaScript APIFor more information, see Overview of Power BI REST API, Power BI .NET SDK and the Power BI JavaScript API.

下载示例Download the sample

本文展示了 GitHub 上“为组织嵌入内容”示例中使用的代码。This article shows the code used in the Embedding for your organization sample on GitHub. 若要按照此演练操作,可以下载这个示例。To follow along with this walkthrough, you can download the sample.

步骤 1 - 在 Azure AD 中注册应用Step 1 - register an app in Azure AD

必须向 Azure AD 注册应用,才能执行 REST API 调用。You will need to register your application with Azure AD in order to make REST API calls. 有关详细信息,请参阅注册 Azure AD 应用以便嵌入 Power BI 内容For more information, see Register an Azure AD app to embed Power BI content.

如果已下载“为组织嵌入内容”示例,请使用注册后获取的客户端 ID,以便此示例能够进行 Azure AD 身份验证。If you downloaded the Embedding for your organization sample, you use the Client ID you get, after registration, so that the sample can authenticate to Azure AD. 若要配置此示例,请在 web.config 文件中更改客户端 ID。To configure the sample, change the clientId in the web.config file.

第 2 步 - 从 Azure AD 获取访问令牌Step 2 - get an access token from Azure AD

在应用内,需要先从 Azure AD 获取访问令牌,再调用 Power BI REST API。Within your application, you will first need to 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.

若要查看相关示例,可以参阅 Controllers\HomeController.cs 中的每个内容项任务。You can see examples of this within each content item task in Controllers\HomeController.cs.

第 3 步 - 获取内容项Step 3 - get a content item

若要嵌入 Power BI 内容,需要执行几项操作,以确保能够正确嵌入内容。To embed your Power BI content, you will need to do a couple of things to make sure it embeds correctly. 虽然可以直接通过 REST API 完成所有这些步骤,但示例应用和本文中的示例都是使用 .NET SDK 执行这些操作。While all of these steps can be done with the REST API directly, the sample application, and the examples here, are made with the .NET SDK.

使用访问令牌创建 Power BI 客户端Create the Power BI Client with your access token

建议使用访问令牌创建 Power BI 客户端对象,以便能够与 Power BI API 进行交互。With your access token, you will want to create your Power BI client object which will allow you to interact with the Power BI APIs. 为此,使用 Microsoft.Rest.TokenCredentials 对象包装 AccessToken。This is done by wrapping the AccessToken with a Microsoft.Rest.TokenCredentials object.

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

var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

// Create a Power BI Client object. It will be used to call Power BI APIs.
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
{
    // Your code to embed items.
}

获取要嵌入的内容项Get the content item you want to embed

使用 Power BI 客户端对象检索对要嵌入的项的引用。Use the Power BI client object to retrieve a reference to the item you want to embed. 可以嵌入仪表板、磁贴或报表。You can embed dashboards, tiles or reports. 下面的示例展示了如何从给定工作区检索首个仪表板、磁贴或报表。Here is an example of how to retrieve the first dashboard, tile or report from a given workspace.

有关示例,请参阅“应用拥有数据”示例的 Controllers\HomeController.cs。A sample of this is available within Controllers\HomeController.cs of the App Owns Data sample.

仪表板Dashboards

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// You will need to provide the GroupID where the dashboard resides.
ODataResponseListDashboard dashboards = client.Dashboards.GetDashboardsInGroup(GroupId);

// Get the first report in the group.
Dashboard dashboard = dashboards.Value.FirstOrDefault();

磁贴Tile

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// To retrieve the tile, you first need to retrieve the dashboard.

// You will need to provide the GroupID where the dashboard resides.
ODataResponseListDashboard dashboards = client.Dashboards.GetDashboardsInGroup(GroupId);

// Get the first report in the group.
Dashboard dashboard = dashboards.Value.FirstOrDefault();

// Get a list of tiles from a specific dashboard
ODataResponseListTile tiles = client.Dashboards.GetTilesInGroup(GroupId, dashboard.Id);

// Get the first tile in the group.
Tile tile = tiles.Value.FirstOrDefault();

报表Report

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// You will need to provide the GroupID where the dashboard resides.
ODataResponseListReport reports = client.Reports.GetReportsInGroupAsync(GroupId);

// Get the first report in the group.
Report report = reports.Value.FirstOrDefault();

创建嵌入令牌Create the embed token

需要生成嵌入令牌,以便能够通过 JavaScript API 使用此令牌。An embed token needs to be generated which can be used from the JavaScript API. 嵌入令牌特定于要嵌入的项。The embed token will be specific to the item you are embedding. 也就是说,只要嵌入 Power BI 内容,就需要为其新建嵌入令牌。This means that any time you embed a piece of Power BI content, you need to create a new embed token for it. 有关详细信息(包括要使用哪个 accessLevel),请参阅 GenerateToken APIFor more information, including which accessLevel to use, see GenerateToken API.

重要

由于嵌入令牌仅用于开发测试,因此 Power BI 主帐户生成的嵌入令牌数量有限。Because embed tokens are intended for development testing only, the number of embed tokens a Power BI master account can generate is limited. 对于嵌入生产方案,必须购买容量A capacity must be purchased for production embedding scenarios. 购买容量后便不会限制嵌入令牌生成。There is no limit to embed token generation when a capacity is purchased.

有关示例,请参阅“为组织嵌入内容”示例的 Controllers\HomeController.cs。A sample of this is available within Controllers\HomeController.cs of the Embedding for your organization sample.

假设为 EmbedConfig 和 TileEmbedConfig 创建了类。This assumes a class is created for EmbedConfig and TileEmbedConfig. Models\EmbedConfig.cs 和 Models\TileEmbedConfig.cs 中提供了相关示例。A sample of these are available within Models\EmbedConfig.cs and Models\TileEmbedConfig.cs.

仪表板Dashboard

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
EmbedToken tokenResponse = client.Dashboards.GenerateTokenInGroup(GroupId, dashboard.Id, generateTokenRequestParameters);

// Generate Embed Configuration.
var embedConfig = new EmbedConfig()
{
    EmbedToken = tokenResponse,
    EmbedUrl = dashboard.EmbedUrl,
    Id = dashboard.Id
};

磁贴Tile

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// Generate Embed Token for a tile.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
EmbedToken tokenResponse = client.Tiles.GenerateTokenInGroup(GroupId, dashboard.Id, tile.Id, generateTokenRequestParameters);

// Generate Embed Configuration.
var embedConfig = new TileEmbedConfig()
{
    EmbedToken = tokenResponse,
    EmbedUrl = tile.EmbedUrl,
    Id = tile.Id,
    dashboardId = dashboard.Id
};

报表Report

using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;

// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
EmbedToken tokenResponse = client.Reports.GenerateTokenInGroup(GroupId, report.Id, generateTokenRequestParameters);

// Generate Embed Configuration.
var embedConfig = new EmbedConfig()
{
    EmbedToken = tokenResponse,
    EmbedUrl = report.EmbedUrl,
    Id = report.Id
};

第 4 步 - 使用 JavaScript 加载项Step 4 - load an item using JavaScript

可以使用 JavaScript 将仪表板载入网页上的 div 元素。You can use JavaScript to load a dashboard into a div element on your web page. 此示例对仪表板、磁贴或报表使用 EmbedConfig/TileEmbedConfig 模型和视图。The sample uses an EmbedConfig/TileEmbedConfig model along with views for a dashboard, tile or report. 有关使用 JavaScript API 的完整示例,可以参阅 Microsoft Power BI 嵌入示例For a full sample of using the JavaScript API, you can use the Microsoft Power BI Embedded Sample.

“为组织嵌入内容”示例中提供了相关应用示例。An application sample of this is available within the Embedding for your organization sample.

Views\Home\EmbedDashboard.cshtmlViews\Home\EmbedDashboard.cshtml

<script src="~/scripts/powerbi.js"></script>
<div id="dashboardContainer"></div>
<script>
    // Read embed application token from Model
    var accessToken = "@Model.EmbedToken.Token";

    // Read embed URL from Model
    var embedUrl = "@Html.Raw(Model.EmbedUrl)";

    // Read dashboard Id from Model
    var embedDashboardId = "@Model.Id";

    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'dashboard',
        tokenType: models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedDashboardId
    };

    // Get a reference to the embedded dashboard HTML element
    var dashboardContainer = $('#dashboardContainer')[0];

    // Embed the dashboard and display it within the div container.
    var dashboard = powerbi.embed(dashboardContainer, config);
</script>

Views\Home\EmbedTile.cshtmlViews\Home\EmbedTile.cshtml

<script src="~/scripts/powerbi.js"></script>
<div id="tileContainer"></div>
<script>
    // Read embed application token from Model
    var accessToken = "@Model.EmbedToken.Token";

    // Read embed URL from Model
    var embedUrl = "@Html.Raw(Model.EmbedUrl)";

    // Read tile Id from Model
    var embedTileId = "@Model.Id";

    // Read dashboard Id from Model
    var embedDashboardeId = "@Model.dashboardId";

    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'tile',
        tokenType: models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedTileId,
        dashboardId: embedDashboardeId
    };

    // Get a reference to the embedded tile HTML element
    var tileContainer = $('#tileContainer')[0];

    // Embed the tile and display it within the div container.
    var tile = powerbi.embed(tileContainer, config);
</script>

Views\Home\EmbedReport.cshtmlViews\Home\EmbedReport.cshtml

<script src="~/scripts/powerbi.js"></script>
<div id="reportContainer"></div>
<script>
    // Read embed application token from Model
    var accessToken = "@Model.EmbedToken.Token";

    // Read embed URL from Model
    var embedUrl = "@Html.Raw(Model.EmbedUrl)";

    // Read report Id from Model
    var embedReportId = "@Model.Id";

    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'report',
        tokenType: models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedReportId,
        permissions: models.Permissions.All,
        settings: {
            filterPaneEnabled: true,
            navContentPaneEnabled: true
        }
    };

    // Get a reference to the embedded report HTML element
    var reportContainer = $('#reportContainer')[0];

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

后续步骤Next steps

可以参考 GitHub 上的示例应用。A sample application is available on GitHub for you to review. 上面的示例均以此示例为依据。The above examples are based on that sample. 有关详细信息,请参阅“为组织嵌入内容”示例For more information, see Embedding for your organization sample.

若要详细了解 JavaScript API,请参阅 Power BI JavaScript APIMore information is available for the JavaScript API, see Power BI JavaScript API.

更多问题?More questions? 尝试咨询 Power BI 社区Try asking the Power BI Community