Power BI 工作区集合入门示例Get started with Power BI Workspace Collections sample

通过 Power BI 工作区集合,可以将 Power BI 报表集成到 Web 或移动应用程序。With Power BI Workspace Collections, you can integrate Power BI reports right into your web or mobile applications. 本文介绍 Power BI 工作区集合入门示例。In this article, we introduce you to the Power BI Workspace Collections get started sample.


Power BI 工作区集合已弃用,到 2018 年 6 月 或合同指示时可用。Power BI Workspace Collections is deprecated and is available until June 2018 or when your contract indicates. 建议你规划到 Power BI Embedded 的迁移以避免应用程序中断。You are encouraged to plan your migration to Power BI Embedded to avoid interruption in your application. 有关如何将数据迁移到 Power BI Embedded 的信息,请参阅如何将 Power BI 工作区集合内容迁移到 Power BI EmbeddedFor information on how to migrate your data to Power BI Embedded, see How to migrate Power BI Workspace Collections content to Power BI Embedded.

在继续之前,需要保存以下资源:将 Power BI 报表集成到示例应用和你自己的应用中时,这些资源都可以提供帮助。Before we go any further, you want to save the following resources: They help you when integrating Power BI reports into the sample app and your own apps too.


需要先在 Azure 订阅中创建至少一个工作区集合才能配置和运行 Power BI 工作区集合入门示例。Before you can configure and run the Power BI Workspace Collections get started sample, you need to create at least one Workspace Collection in your Azure subscription. 若要了解如何在 Azure 门户中创建工作区集合,请参阅 Power BI 工作区集合入门To learn how to create a Workspace Collection in the Azure portal, see Getting Started with Power BI Workspace Collections.

配置示例应用Configure the sample app

下面引导完成 Visual Studio 开发环境的设置,以便访问运行示例应用时所需的组件。Let's walk through setting up your Visual Studio development environment to access the components needed to run the sample app.

  1. 下载并解压缩 GitHub 上的 Power BI 工作区集合 - 将报表集成到 Web 应用中示例。Download and unzip the Power BI Workspace Collections - Integrate a report into a web app sample on GitHub.


    本示例中的某些 URL 只能在全球环境中使用。Some URLs in this sample can only be used in global environment. 若要在 Azure 中国区环境中使用它,必须执行一些替换。To make it work in Azure China environment, you have to do some replacement. 例如:将 https://api.powerbi.com 替换为 https://api.powerbi.cn,将 https://management.azure.com 替换为文件 \ProvisionSample\App.config 中的 https://management.chinacloudapi.cn,将 https://management.core.windows.net 替换为文件 \ProvisionSample\Program.cs 中的 https://management.core.chinacloudapi.cn,将 https://login.windows.net 替换为文件\ProvisionSample\ProgramExtensions.cs 中的 https://login.chinacloudapi.cn。For example: replace https://api.powerbi.com with https://api.powerbi.cn, replace https://management.azure.com with https://management.chinacloudapi.cn in file \ProvisionSample\App.config, replace https://management.core.windows.net with https://management.core.chinacloudapi.cn in file \ProvisionSample\Program.cs, replace https://login.windows.net with https://login.chinacloudapi.cn in file \ProvisionSample\ProgramExtensions.cs. 有关全球环境与中国区环境中 URL 的差别的详细信息,请参阅 此文For more details on the url difference between global and China, please see here.

  2. 在 Visual Studio 中打开“PowerBI embedded.sln” 。Open PowerBI-embedded.sln in Visual Studio. 可能需要在 NuGet 程序包管理器控制台中执行 Update-Package 命令来更新此解决方案中使用的程序包。You may need to execute the Update-Package command in the NuGet Package Manager Console in order to update the packages used in this solution.

  3. 生成解决方案。Build the solution.

  4. 运行“ProvisionSample” 控制台应用。Run the ProvisionSample console app. 在示例控制台应用中,预配一个工作区并导入 PBIX 文件。In the sample console app, you provision a workspace and import a PBIX file.

  5. 要预配新的工作区,请选择选项 1“收集管理”,并选择选项 6“预配新的工作区”To provision a new Workspace, select option 1, Collection management, and then select option 6, Provision a new Workspace

  6. 要导入新的“报表”,请选择选项 2“报表管理”,然后选择选项 3“将 PBIX 桌面文件导入到工作区”。To import a new Report, select option 2, Report management, and then select option 3, Import PBIX Desktop file into a workspace.

  7. 输入工作区集合名称和访问密钥Enter your Workspace Collection name, and Access Key. 可以通过 Azure 门户获取这些信息。You can get these in the Azure portal. 若要详细了解如何获取访问密钥,请参阅“Power BI Embedded 入门”中的查看 Power BI API 访问密钥To learn more about how to get your Access Key, see View Power BI API Access Keys in Get started with Power BI Embedded.

    Azure 门户中的访问密钥

  8. 复制并保存新创建的 工作区 ID 以便在本文后面部分使用。Copy and save the newly created Workspace ID to use later in this article. 创建工作区 ID 之后,可以在 Azure 门户中找到该数据。After the Workspace ID is created, you can find it the Azure portal.

    Azure 门户中的工作区 ID

  9. 要将 PBIX 文件导入到工作区,请选择选项 6 “将 PBIX 文件导入到现有工作区”。To import a PBIX file into your Workspace, select option 6. Import PBIX Desktop file into an existing workspace. 如果没有现有的 PBIX 文件,则可以下载 Retail Analysis Sample PBIX(零售分析示例 PBIX)。If you don't have a PBIX file handy, you can download the Retail Analysis Sample PBIX.

  10. 如果出现提示,请为数据集输入一个易记的名称。If prompted, enter a friendly name for your Dataset.

应该会看到如下所示的响应:You should see a response like:

Checking import state... Publishing
Checking import state... Succeeded


如果 PBIX 文件包含任何直接查询连接,请选择选项 7 以更新连接字符串。If your PBIX file contains any direct query connections, run option 7 to update the connection strings.

此时, 工作区中已导入了一个 Power BI PBIX 报表。At this point, you have a Power BI PBIX report imported into your Workspace. 接下来将演示如何运行 Power BI 工作区集合入门示例 Web 应用。Now, let's look at how to run the Power BI Workspace Collections get started sample web app.

运行示例 Web 应用Run the sample web app

Web 应用示例是一个示例应用程序,用于呈现工作区中导入的报表。The web app sample is a sample application that renders reports imported into your Workspace. 下面介绍了如何配置 Web 应用示例。Here's how to configure the web app sample.

  1. PowerBI Embedded Visual Studio 解决方案中,右键单击“EmbedSample”Web 应用程序,并选择“设为启动项目”。In the PowerBI-embedded Visual Studio solution, right-click the EmbedSample web application, and choose Set as StartUp project.

  2. web.config 中,在 EmbedSample Web 应用程序中,编辑 appSettingsAccessKeyWorkspaceCollection 名称和 WorkspaceIdIn web.config, in the EmbedSample web application, edit the appSettings: AccessKey, WorkspaceCollection name, and WorkspaceId.

        <add key="powerbi:AccessKey" value="" />
        <add key="powerbi:ApiUrl" value="https://api.powerbi.cn" />
        <add key="powerbi:WorkspaceCollection" value="" />
        <add key="powerbi:WorkspaceId" value="" />
  3. 运行 EmbedSample Web 应用程序。Run the EmbedSample web application.

运行 EmbedSample Web 应用程序后,左侧的导航面板应包含“报表”菜单。Once you run the EmbedSample web application, the left navigation panel should contain a Reports menu. 如果要查看导入的报表,请展开“报表” ,并单击任一报表。To view the report you imported, expand Reports, and click a report. 如果已导入了 Retail Analysis Sample PBIX(零售分析示例 PBIX),则示例 Web 应用将如下所示:If you imported the Retail Analysis Sample PBIX, the sample web app would look like this:


单击某个报表后, EmbedSample Web 应用程序应类似于以下内容:After you click a report, the EmbedSample web application should look something this:


探索示例代码Explore the sample code

Power BI 工作区集合示例是一个 Web 应用示例,演示了如何将 Power BI 报表集成到应用中。The Power BI Workspace Collections sample is an example web app that shows you how to integrate Power BI reports into your app. 它采用模型-视图-控制器 (MVC) 设计模式来演示最佳做法。It uses a Model-View-Controller (MVC) design pattern to demonstrate best practices. 本部分重点介绍可以在 PowerBI Embedded Web 应用解决方案中浏览的示例代码。This section highlights parts of the sample code that you can explore within the PowerBI-embedded web app solution. 模型-视图-控制器 (MVC) 模式根据用户输入的三个单独的类(模型、视图和控件)对域、演示文稿和操作分开进行建模。The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes: Model, View, and Control. 若要了解关于 MVC 的详细信息,请参阅 Learn About ASP.NET(了解 ASP.NET)。To learn more about MVC, see Learn About ASP.NET.

Power BI 工作区集合示例代码分隔方式如下所示。The Power BI Workspace Collections sample code is separated as follows. 每个部分在 PowerBI embedded.sln 解决方案中都包括了文件名称,以便轻松查找示例中的代码。Each section includes the file name in the PowerBI-embedded.sln solution so that you can easily find the code in the sample.


本节总结了演示如何编写代码的示例代码。This section is a summary of the sample code that shows how the code was written. 若要查看完整的示例,请加载 Visual Studio 中的 PowerBI embedded.sln 解决方案。To view the complete sample, please load the PowerBI-embedded.sln solution in Visual Studio.


该示例包含 ReportsViewModelReportViewModelThe sample has a ReportsViewModel and ReportViewModel.

ReportsViewModel.cs:表示多个 Power BI 报表。ReportsViewModel.cs: Represents Power BI Reports.

public class ReportsViewModel
    public List<Report> Reports { get; set; }

ReportViewModel.cs:表示一个 Power BI 报表。ReportViewModel.cs: Represents a Power BI Report.

public classReportViewModel
    public IReport Report { get; set; }

    public string AccessToken { get; set; }

连接字符串Connection string

连接字符串必须采用以下格式:The connection string must be in the following format:

Data Source=tcp:MyServer.database.chinacloudapi.cn,1433;Initial Catalog=MyDatabase

使用一般的服务器和数据库属性会失败。Using common server and database attributes fail. 例如:Server=tcp:MyServer.database.chinacloudapi.cn,1433;Database=MyDatabase,For example: Server=tcp:MyServer.database.chinacloudapi.cn,1433;Database=MyDatabase,


视图用于管理多个 Power BI 报表或一个 Power BI 报表的显示情况。The View manages the display of Power BI Reports and a Power BI Report.

Reports.cshtml:循环访问 Model.Reports 以创建 ActionLinkReports.cshtml: Iterate over Model.Reports to create an ActionLink. ActionLink 包含以下内容:The ActionLink is composed as follows:

部分Part 说明Description
标题Title 报表的名称。Name of the Report.
QueryStringQueryString 指向报表 ID 的链接。A link to the Report ID.
<div id="reports-nav" class="panel-collapse collapse">
    <div class="panel-body">
        <ul class="nav navbar-nav">
            @foreach (var report in Model.Reports)
                var reportClass = Request.QueryString["reportId"] == report.Id ? "active" : "";
                <li class="@reportClass">
                    @Html.ActionLink(report.Name, "Report", new { reportId = report.Id })

Report.cshtml:为 PowerBIReportFor 设置 Model.AccessToken 和 Lambda 表达式。Report.cshtml: Set the Model.AccessToken, and the Lambda expression for PowerBIReportFor.

@model ReportViewModel


<div class="side-body padding-top">
    @Html.PowerBIReportFor(m => m.Report, new { style = "height:85vh" })


DashboardController.cs:创建用于传递应用令牌 的 PowerBIClient。DashboardController.cs: Creates a PowerBIClient passing an app token. JSON Web 令牌 (JWT) 是基于签名密钥生成的,用于获取凭据A JSON Web Token (JWT) is generated from the Signing Key to get the Credentials. 凭据用于创建 PowerBIClient 实例。The Credentials are used to create an instance of PowerBIClient. 创建 PowerBIClient 实例后,可以调用 GetReports() 和 GetReportsAsync()。Once you have an instance of PowerBIClient, you can call GetReports() and GetReportsAsync().


    private IPowerBIClient CreatePowerBIClient()
        var credentials = new TokenCredentials(accessKey, "AppKey");
        var client = new PowerBIClient(credentials)
            BaseUri = new Uri(apiUrl)

        return client;

ActionResult Reports()ActionResult Reports()

    public ActionResult Reports()
        using (var client = this.CreatePowerBIClient())
            var reportsResponse = client.Reports.GetReports(this.workspaceCollection, this.workspaceId);

            var viewModel = new ReportsViewModel
                Reports = reportsResponse.Value.ToList()

            return PartialView(viewModel);

任务报表 (string reportId)Task Report(string reportId)

    public async Task<ActionResult> Report(string reportId)
        using (var client = this.CreatePowerBIClient())
            var reportsResponse = await client.Reports.GetReportsAsync(this.workspaceCollection, this.workspaceId);
            var report = reportsResponse.Value.FirstOrDefault(r => r.Id == reportId);
            var embedToken = PowerBIToken.CreateReportEmbedToken(this.workspaceCollection, this.workspaceId, report.Id);

            var viewModel = new ReportViewModel
                Report = report,
                AccessToken = embedToken.Generate(this.accessKey)

            return View(viewModel);

将报表集成到应用中Integrate a report into your app

创建报表后,可以使用 IFrame 嵌入 Power BI 报表Once you have a Report, you use an IFrame to embed the Power BI Report. 以下是来自 Power BI 工作区集合示例中的 powerbi.js 代码片段。Here is a code snippet from powerbi.js in the Power BI Workspace Collections sample.

init: function() {
    var embedUrl = this.getEmbedUrl();
    var iframeHtml = '<iframe style="width:100%;height:100%;" src="' + embedUrl + 
        '" scrolling="no" allowfullscreen="true"></iframe>';
    this.element.innerHTML = iframeHtml;
    this.iframe = this.element.childNodes[0];
    this.iframe.addEventListener('load', this.load.bind(this), false);

筛选应用程序中嵌入的报表Filter reports embedded in your application

可以使用 URL 语法筛选嵌入的报表。You can filter an embedded report using a URL syntax. 要进行筛选,可以使用指定的筛选器将带运算符 eq$filter 查询字符串参数添加到 iFrame src url。To do this, you add a $filter query string parameter with an eq operator to your iFrame src url with the filter specified. 以下为筛选查询语法:Here is the filter query syntax:



{tableName/fieldName} 不能包含空格或特殊字符。{tableName/fieldName} cannot include spaces or special characters. {fieldValue} 接受单个分类值。The {fieldValue} accepts a single categorical value.

另请参阅See also

常见 Power BI 工作区集合方案Common Power BI Workspace Collection scenarios
在 Power BI 工作区集合中进行身份验证和授权Authenticating and authorizing in Power BI Workspace Collections
嵌入报表Embed a report
从数据集创建新报表Create a new report from a dataset
Power BI DesktopPower BI Desktop
JavaScript 嵌入示例JavaScript Embed Sample

有更多问题?More questions? 试用 Power BI 社区Try the Power BI Community