为组织将报表集成到应用中Integrate a report into an app for your organization

了解如何在为组织嵌入内容时,通过调用 REST API 和 Power BI JavaScript API,将报表集成到或嵌入 Web 应用中。Learn how to integrate, or embed, a report into a web app using REST API calls along with the Power BI JavaScript API when embedding for your organization.

嵌入的报表示例

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

备注

要改用 EmbedToken 为客户嵌入报表吗?Looking to embed a report for your customers, using an embedtoken, instead? 请参阅为客户将仪表板、磁贴或报表集成到应用中See, Integrate a dashboard, tile, or report into your application for your customers.

若要将报表集成到 Web 应用中,请使用 Power BI REST API/Power BI C# SDK 和 Azure Active Directory (AD) 授权访问令牌来获取报表。To integrate a report into a web app, you use the Power BI REST API, or the Power BI C# SDK, and an Azure Active Directory (AD) authorization access token to get a report. 然后,使用相同的访问令牌加载报表。Then, you load the report using the same access token. Power BI API 向某些 Power BI 资源提供了编程访问权限。The Power BI API provides programmatic access to certain Power BI resources. 有关详细信息,请参阅 Power BI REST APIPower BI JavaScript APIFor more information, see Power BI REST API and the Power BI JavaScript API.

下载示例Download the sample

本文展示了 GitHub 上 integrate-report-web-app 中使用的代码。This article shows the code used in the integrate-report-web-app on GitHub. 若要按照此演练操作,可以下载这个示例。To follow along with this walkthrough, you can download the sample.

还可使用载入体验工具快速开始并下载示例应用程序。You can also go through the Onboarding experience tool to quickly get started and download a sample application.

但是,如果选择手动设置环境,则可以继续进行下面的操作。However, if you choose to set up the environment manually, you can continue below.

步骤 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.

如果已下载integrate-report-web-app,请使用注册后获取的客户端 ID 和客户端密码,以便此示例能够进行 Azure AD 身份验证。If you downloaded the integrate-report-web-app, you use the Client ID and Client Secret you get, after registration, so that the sample can authenticate to Azure AD. 若要配置此示例,请在 cloud.config 文件中更改客户端 ID 和客户端密码。To configure the sample, change the Client ID and Client Secret in the cloud.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.

第 3 步 - 获取报表Step 3 - get a report

若要获取 Power BI 报表,请使用获取报表操作,它将获取 Power BI 报表的列表。To get a Power BI report, you use the Get Reports operation which gets a list of Power BI reports. 在报表列表中,可以获取报表 ID。From the list of reports, you can get a report id.

使用访问令牌获取报表Get reports using an access token

使用在第 2 步中检索的访问令牌,可以调用获取报表操作。With the access token you retrieved in step 2, you can call the Get Reports operation. 获取报表操作将返回报表的列表。The Get Reports operation returns a list of reports. 可以获取报表列表中的一个报表。You can get a single report from the list of reports. 下面是获取报表的完整 C# 方法。Below is a complete C# method to get a report.

若要执行 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

Default.aspx.csDefault.aspx.cs

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 name { get; set; }
    public string webUrl { get; set; }
    public string embedUrl { get; set; }
}

使用 .NET SDK 获取报表Get reports 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.

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 will be 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;
}

第 4 步 - 使用 JavaScript 加载报表Step 4 - load a report using JavaScript

可以使用 JavaScript 将报表加载到网页上的 div 元素中。You can use JavaScript to load a report into a div element on your web page.

Default.aspxDefault.aspx

<!-- 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", updateEmbedReporte, 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/>";
    });
}

如果下载并运行了 integrate-report-web-app,示例将如下所示。If you downloaded and ran the integrate-report-web-app, the sample will look similar to below.

嵌入的报表示例

使用组(应用工作区)Working with groups (app workspaces)

若要从组(应用工作区)嵌入报表,建议执行以下 REST API 调用,获取组仪表板中所有可用报表的列表。For embedding a report from a group (app workspace), you will want to get the list of all available reports within a group's dashboard using the following REST API call. 若要详细了解此 REST API 调用,请参阅获取报表To find more information about this REST API call, see Get Reports. 必须在组中拥有权限,请求才能返回结果。You will need to have permission in the group for the request to return results.

https://api.powerbi.com/v1.0/myorg/groups/{group_id}/reports

上面的 API 返回可用报表列表。The above API returns the list of the available reports. 每个报表都有已创建的 EmbedUrl 属性,此属性支持组嵌入。Each report has an EmbedUrl property which is already constructed to support group embedding.

https://app.powerbi.com/reportEmbed?reportId={report_id}&groupId={group_id}

后续步骤Next steps

可以参考 GitHub 上的示例应用。A sample application is available on GitHub for you to review. 有关详细信息,请参阅 integrate-report-web-appFor more information, see integrate-report-web-app.

若要详细了解 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