POWEWR BI嵌入 WEB

欢迎关注我的公众号

内容

  1. Power BI报表嵌入WEB三种方式、

前两种已经实践可行,第三中还没有实际实践,只给出了步骤

  1. Power BI报表嵌入WEB方式一
      1. 发布操作

将power bi 发布到云上后,打开我的工作区,点击文件选择发布到Web

 

点击创建嵌入代码

 

点击发布

 

点击关闭完成操作;

url:互联网任何人访问该url,都可以查看该报表

嵌入HTML:直接放入前端网页代码中即可,但需要支持iframe

 

      1. 报表更新

在你创建发布到 Web 嵌入代码并将其共享后,将使用进行的所有更改对报表进行更新。 但是,务必要了解你的用户可能需要一段时间才能看到更新。 报表或视觉对象更新大约需要一小时才会反映在发布到 Web 嵌入代码中。

当你最初使用发布到 Web 获取嵌入代码时,嵌入代码链接立即处于活动状态,且任何打开该链接的人均可查看。 在初始发布到 Web 操作后,发布到 Web 链接指向的报表或视觉对象的更新大约需要一小时才可供你的用户查看。

若要了解详细信息,请参阅本文后面工作方式部分。 如果你需要更新以便立即可用,可以删除嵌入代码并创建一个新的代码。

 

      1. 数据刷新

 

数据刷新自动反映在嵌入的报表或视觉对象中。 大约需要 1 小时才可从嵌入代码中看到刷新的数据。 选择报表所用数据集计划上的不刷新可以禁用自动刷新。

      1. 限制

 

发布到 Web 支持 Power BI 服务中绝大部分数据源和报表,但以下内容目前不受支持或不可用于发布到 Web:

1使用行级别安全性的报表。

2使用实时连接数据源的报表,包括在本地托管的 Analysis Services 表格、Analysis Service Multidimensional、Azure Analysis Services 以及 Power BI 服务。

3直接或通过组织内容包共享的报表。

4你不是编辑成员的组中的报表。

5“发布到 Web”报表中当前不支持“R”视觉对象。

      1. 工作方式

 

当你使用发布到 Web 创建嵌入代码时,报表对 Internet 上的用户均可见。 它是公开提供的,因此你可以期望将来查看者能够轻松地通过社交媒体共享报表。 用户查看报表,或者通过打开直接公共 URL,或者在嵌入到的网页或博客中查看,Power BI 将缓存报表定义和查看报表所需的查询结果。 此方法确保报表可供成千上万的并发用户查看,且不会对性能产生任何影响。

缓存持续很长时间,因此如果你更新报表定义(例如更改其视图模式)或刷新报表数据,大约需要一小时才能在用户查看的报表版本中反映更改。 因此建议你提前暂存工作,并仅当你对设置满意时创建发布到 Web 嵌入代码。

附上官网教材:https://docs.microsoft.com/zh-cn/power-bi/service-publish-to-web#how-it-works-technical-details

 

 

 

 

  1. 通过Power BI Embedded嵌入

目前国内版本Azure由21世纪互联进行代理,只支持由nodejs,c#,JavaScript语言写的网站

      1. 注册订阅Azure

如果不进行订阅,是无法进行后续步骤;点击网址https://www.azure.cn/

该网址是21 世纪互联代理的云服务;点击试用,完成申请后使用获得的账号进行登陆,打开工作界面如下:

 

 

 

      1. 新建Power BI工作区集合

点击创建资源,搜索 power即可找到 Power BI Embedded,打开Power BI Embedded;

 

点击创建

 

 

输入信息,点击创建

完成创建后界面如下:

      1. 查看 Power BI API 访问密钥

调用 Power BI REST API 所需的最重要信息之一是访问键。 这些访问键用于生成对 API 请求进行身份验证的应用程序令牌 。

 

      1. 安装Visual Studio

软件下载地址:https://www.nuget.org/downloads

在以后的使用过程中有时会提示安装新的加载项才能生成新的解决方案,点击安装即可;

 

 

      1. 创建工作区并上传PBIX文件

1. 下载并解压缩 GitHub 上的Power BI Embedded - Integrate a report into a web app(Power BI Embedded - 将报表集成到 Web 应用中)示例。

2. 在 Visual Studio 中打开“PowerBI embedded.sln”。可能需要在 NuGET 程序包管理器控制台中执行“Update-Package”命令来更新此解决方案中使用的程序包

3. 生成解决方案

注意:生成解决方案之前,需要用全局替换将api.powerbi.com替换api.powerbi.cn

 

4. 右键设置ProvisionSample为启动项,启动ProvisionSample

 

 

 

 

 

 

 

 

 

 

 

 

5. 选择1  - collection management ,接下来选择6 – provision a new workspace,创建一个新的Workspace Id。复制并保存Workspace Id(集合名词和密钥等信息,可以在Azure门户预览中获取)

 

6.找到自己等待上传的PBIX文件

 

7. 选择7–Exit group,选择2 – Report management ,3-Import PBIX Desktop file into a workspace, 导入PBIX文件

 

 

 

 

      1. 运行WEB应用

1.  在 PowerBI Embedded Visual Studio 解决方案中,右键单击 EmbedSample Web 应用,然后选择“设为启动项目”。

 

2.  在 web.config 的 EmbedSample Web 应用程序中,编辑 appSettings 中的 AccessKey 和 WorkspaceCollection 名称,以及 WorkspaceId。

附上代码直接替换原有的

<appSettings>

    <add key="powerbi:AccessKey" value="" />

    <add key="powerbi:ApiUrl" value="https://api.powerbi.cn" />

    <add key="powerbi:WorkspaceCollection" value="" />

    <add key="powerbi:WorkspaceId" value="" />

</appSettings>

 

运行

 

 

 

 

  1. 通过Power BI Service嵌入

使用国际版的Azure进行实现

      1. 注册订阅Azure

免费注册网址https://azure.microsoft.com/zh-cn/

选择获取免费账户,免费开始,点击创建一个如下图:

 

完成注册后进入如下界面:

 

 

      1. Azure AD 中注册应用
  1. 在 Azure 门户中,转到应用注册,再选择要用于嵌入内容的应用。

https://docs.microsoft.com/zh-cn/power-bi/developer/media/register-app/powerbi-embedded-azuread-registered-apps.png

  1. 在“API 访问权限”下选择“所需权限”。

https://docs.microsoft.com/zh-cn/power-bi/developer/media/register-app/powerbi-embedded-azuread-app-required-permissions.png

 

  1. 选择“Windows Azure Active Directory”并请务必选中以登录用户身份访问目录 选择保存
  2.  
  3. https://docs.microsoft.com/zh-cn/power-bi/developer/media/register-app/powerbi-embedded-azuread-app-permissions01.png

     

  4. 在“所需权限”中,选择“Power BI 服务 (Power BI)”。
  5. https://docs.microsoft.com/zh-cn/power-bi/developer/media/register-app/powerbi-embedded-azuread-app-permissions03.png

     

    备注

    如果直接在 Azure AD 门户中创建了应用,可能看不到“Power BI 服务(Power BI)”。 如果不存在,请选择“+ 添加”,然后选择“1 选择和 API”。 在 API 列表中选择“Power BI 服务”,然后选择“选择”。 如果“+ 添加”中没有“Power BI 服务(Power BI)”,请至少使用一个用户注册 Power BI。

     

  6. 选择“委派权限”下的所有权限。 需要逐一选中这些选项才能保存所做的选择。 完成时选择“保存”。
  7. https://docs.microsoft.com/zh-cn/power-bi/developer/media/register-app/powerbi-embedded-azuread-app-permissions04.png

     

  8. 在“所需权限”中,选择“授予权限”。必须为“主帐户”调用“授予权限”操作,以免 Azure AD 提示提供内容。 如果执行此操作的帐户是全局管理员,将向组织内此应用的所有用户授予权限。 如果执行此操作的帐户是主帐户,而不是全局管理员,将仅向此应用的主帐户授予权限。
  9.  

      1. 下载示例
  10. 示例网址:

    https://github.com/Microsoft/PowerBI-Developer-Samples/tree/master/User%20Owns%20Data/integrate-report-web-app

    请使用注册后获取的客户端 ID 和客户端密码,以便此示例能够进行 Azure AD 身份验证。 若要配置此示例,请在 cloud.config 文件中更改客户端 ID 和客户端密码。

     

      1. Azure AD 获取访问令牌
  11. 获取访问令牌的第一步是从 Azure AD 获取授权代码。 若要执行此操作,请构造具有以下属性的查询字符串,并重定向到 Azure AD。
  12. 授权代码查询字符串

    var @params = new NameValueCollection

    {

        //Azure AD will return an authorization code.

        //See the Redirect class to see how "code" is used to AcquireTokenByAuthorizationCode

        {"response_type", "code"},

     

        //Client ID is used by the application to identify themselves to the users that they are requesting permissions from.

        //You get the client id when you register your Azure app.

        {"client_id", Properties.Settings.Default.ClientID},

     

        //Resource uri to the Power BI resource to be authorized

        // https://analysis.windows.net/powerbi/api

        {"resource", Properties.Settings.Default.PowerBiAPI},

     

        //After user authenticates, Azure AD will redirect back to the web app

        {"redirect_uri", "http://localhost:13526/Redirect"}

    };

     

  13. 构造查询字符串后,重定向到 Azure AD 以获取授权代码。 下面是构造授权代码查询字符串的并重定向到 Azure AD 的完整 C# 方法。 获取授权代码后,将使用授权代码获取访问令牌。
  14. 然后,在 redirect.aspx.cs 中,调用 AuthenticationContext.AcquireTokenByAuthorizationCode 生成令牌。

    获取授权代码

    protected void signInButton_Click(object sender, EventArgs e)

    {

        //Create a query string

        //Create a sign-in NameValueCollection for query string

        var @params = new NameValueCollection

        {

            //Azure AD will return an authorization code.

            //See the Redirect class to see how "code" is used to AcquireTokenByAuthorizationCode

            {"response_type", "code"},

     

            //Client ID is used by the application to identify themselves to the users that they are requesting permissions from.

            //You get the client id when you register your Azure app.

            {"client_id", Properties.Settings.Default.ClientID},

     

            //Resource uri to the Power BI resource to be authorized

            // https://analysis.windows.net/powerbi/api

            {"resource", Properties.Settings.Default.PowerBiAPI},

     

            //After user authenticates, Azure AD will redirect back to the web app

            {"redirect_uri", "http://localhost:13526/Redirect"}

        };

     

        //Create sign-in query string

        var queryString = HttpUtility.ParseQueryString(string.Empty);

        queryString.Add(@params);

     

        //Redirect authority

        //Authority Uri is an Azure resource that takes a client id to get an Access token

        // AADAuthorityUri = https://login.windows.net/common/oauth2/authorize/

        string authorityUri = Properties.Settings.Default.AADAuthorityUri;

        var authUri = String.Format("{0}?{1}", authorityUri, queryString);

        Response.Redirect(authUri);

    }

  15. 通过授权代码获取访问令牌现在应该已有从 Azure AD 获取的授权代码。 Azure AD 使用授权代码重定向回 Web 应用后,请使用授权代码获取访问令牌。 下面的 C# 示例可用于重定向页和 default.aspx 页的 Page_Load 事件。可以从 Active Directory 身份验证库 NuGet 包检索 Microsoft.IdentityModel.Clients.ActiveDirectory 命名空间。

    Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory

     

    Redirect.aspx.cs

    using Microsoft.IdentityModel.Clients.ActiveDirectory;

    protected void Page_Load(object sender, EventArgs e)

    {

        //Redirect uri must match the redirect_uri used when requesting Authorization code.

        string redirectUri = String.Format("{0}Redirect", Properties.Settings.Default.RedirectUrl);

        string authorityUri = Properties.Settings.Default.AADAuthorityUri;

        // Get the auth code

        string code = Request.Params.GetValues(0)[0];

        // Get auth token from auth code

        TokenCache TC = new TokenCache();

        AuthenticationContext AC = new AuthenticationContext(authorityUri, TC);

        ClientCredential cc = new ClientCredential

            (Properties.Settings.Default.ClientID,

            Properties.Settings.Default.ClientSecret);

        AuthenticationResult AR = AC.AcquireTokenByAuthorizationCode(code, new Uri(redirectUri), cc);

        //Set Session "authResult" index string to the AuthenticationResult

        Session[_Default.authResultString] = AR;

        //Redirect back to Default.aspx

        Response.Redirect("/Default.aspx");

    }

     

    Default.aspx

    using Microsoft.IdentityModel.Clients.ActiveDirectory;

     

    protected void Page_Load(object sender, EventArgs e)

    {

        //Test for AuthenticationResult

        if (Session[authResultString] != null)

        {

            //Get the authentication result from the session

            authResult = (AuthenticationResult)Session[authResultString];

     

            //Show Power BI Panel

            signInStatus.Visible = true;

            signInButton.Visible = false;

            //Set user and token from authentication result

            userLabel.Text = authResult.UserInfo.DisplayableId;

            accessTokenTextbox.Text = authResult.AccessToken;

        }

    }

     

      1. 获取报表
  16. 获取报表操作;它将获取 Power BI 报表的列表。 在报表列表中,可以获取报表 ID。

    Body schema

    Reports have a GUID id, name, webUrl, and embedUrl. You use the embedUrl to embed a report in an app.

     

    {

      "odata.context": "string",

      "value": [

        {

          "id": "string",

          "name": "string",

          "webUrl": "string",

          "embedUrl": "string",

          "datasetId": "string"

        }

      ]

    }

     

    Body Example

    The following is an example of a JSON response with one report.

     

      "@odata.context":"https://api.powerbi.com/v1.0/myorg/$metadata#reports","value":[ 

      { 

          "id":"84dbd390-464a-44d4-8502-5eb9fe91cdba", 

          "name":"AdventureWorks", 

          "webUrl":"https:// app.powerbi.com/reports/84dbd390-464a-44d4-8502-5eb9fe91cdba", 

          "embedUrl":"https://app.powerbi.com/embedReport?reportId=84dbd390-464a-44d4-8502-5eb9fe91cdba" 

        } 

      ] 

    }

     

     

    使用在第 3.1.4步中检索的访问令牌,可以调用获取报表操作。 获取报表操作将返回报表的列表。 可以获取报表列表中的一个报表。 下面是获取报表的完整 C# 方法。

    若要执行 REST API 调用,必须添加格式为“持有者 {访问令牌}”的授权标头。

    使用 REST API 获取报表

    Default.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 获取报表

    可以使用 .NET SDK 检索报表列表,而不用直接调用 REST API。

    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;

    }

      1. 使用 JavaScript 加载报表
  17. 可以使用 JavaScript 将报表加载到网页上的 div 元素中。

    Default.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.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/>";

        });

    }

      1. 运行
  18. 运行效果如下图

  19.  

     

     

     

     

     

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值