步驟 4:取得資料集,以便將資料列加入 Power BI 資料表Step 4: Get a dataset to add rows into a Power BI table

本文屬於將資料推送至資料集逐步解說的一部分。This article is part of a step-by-step walkthrough to push data into a dataset.

在<將資料推送至資料集>的步驟 3 在 Power BI 中建立資料集中,您呼叫了建立資料集作業,以在 Power BI 中建立資料集。In step 3 of Push data into a dataset, Create a dataset in Power BI, you called the Create Dataset operation to create a dataset in Power BI. 在此步驟中,您會使用取得資料集作業和 Newtonsoft.Json 來取得資料集識別碼。您使用步驟 4 中的資料集識別碼將資料列加入資料集。In this step, you use the Get Datasets operation and Newtonsoft.Json to get a dataset id. You use the dataset id in step 4 to add rows to a dataset.

若要將資料推送至 Power BI 資料集,您需要參考資料集中的資料表。To push data into a Power BI dataset, you need to reference the table in the dataset. 若要參考資料集中的資料表,您首先需要取得 資料集識別碼To reference a table in a dataset, you first need to get a Dataset ID. 您可使用取得資料集作業來取得資料集識別碼You get a Dataset ID using the Get Dataset operation. 取得資料集作業會傳回 JSON 字串,包含 Power BI 中的所有資料集清單。The Get Dataset operation returns a JSON string containing a list of all datasets in Power BI. 建議使用 Newtonsoft.Json 還原序列化 JSON 字串。The recommended way to deserialize a JSON string is with Newtonsoft.Json.

以下是取得資料集的方式。Here's how you get a dataset.

取得 Power BI 資料集Get a Power BI dataset

注意:開始使用之前,請確定您已經執行過先前將資料推送至資料集逐步解說中的先前步驟。NOTE: Before you get started, make sure you have followed the previous steps in the push data into a dataset walkthrough.

  1. 在<步驟 2:推送資料的逐步解說>所建立主控台應用程式專案的取得驗證存取權杖中,安裝 Newtonsoft.Json NuGet 套件。In the Console Application project you created in Step 2: Walkthrough to push data, Get an authentication access token, install the Newtonsoft.Json NuGet package. 安裝套件的方法如下:Here's how to install the package:

    a.a. 在 Visual Studio 2015 中,選擇 工具 > NuGet 套件管理員 > 套件管理器主控台In Visual Studio 2015, choose Tools > NuGet Package Manager > Package Manager Console.

    b.b. 在 [套件管理器主控台] 中,輸入 Install-Package Newtonsoft.Json。In Package Manager Console, enter Install-Package Newtonsoft.Json.

  2. 安裝套件之後,將 using Newtonsoft.Json; 加入 Program.cs。After the package is installed, add using Newtonsoft.Json; to Program.cs.
  3. 在 Program.cs 中,加入下列程式碼以取得 資料集識別碼In Program.cs, add the code below to get a Dataset ID.
  4. 執行主控台應用程式,然後登入您的 Power BI 帳戶。Run the Console App, and login to your Power BI account. 您應該會看到 Dataset ID: 後面接著 [主控台視窗] 中的識別碼。You should see Dataset ID: followed by an id in the Console Window.

取得資料集的範例Sample get a dataset

將此程式碼加入 Program.cs 中。Add this code into Program.cs.

  • 在 static void Main(string[] args) 中:In static void Main(string[] args):

    static void Main(string[] args)
    {
    
      //Get an authentication access token
      token = GetToken();
    
      //Create a dataset in Power BI
      CreateDataset();
    
      //Get a dataset to add rows into a Power BI table
      string datasetId = GetDataset();
    }
    
  • 加入 GetDatset() 方法:Add a GetDatset() method:

      #region Get a dataset to add rows into a Power BI table
      private static string GetDataset()
      {
          string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";
          //POST web request to create a dataset.
          //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets
          HttpWebRequest request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
          request.KeepAlive = true;
          request.Method = "GET";
          request.ContentLength = 0;
          request.ContentType = "application/json";
    
          //Add token to the request header
          request.Headers.Add("Authorization", String.Format("Bearer {0}", token));
    
          string datasetId = string.Empty;
          //Get HttpWebResponse from GET request
          using (HttpWebResponse httpResponse = request.GetResponse() as System.Net.HttpWebResponse)
          {
              //Get StreamReader that holds the response stream
              using (StreamReader reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
              {
                  string responseContent = reader.ReadToEnd();
    
                  //TODO: Install NuGet Newtonsoft.Json package: Install-Package Newtonsoft.Json
                  //and add using Newtonsoft.Json
                  var results = JsonConvert.DeserializeObject<dynamic>(responseContent);
    
                  //Get the first id
                  datasetId = results["value"][0]["id"];
    
                  Console.WriteLine(String.Format("Dataset ID: {0}", datasetId));
                  Console.ReadLine();
    
                  return datasetId;
              }
          }
      }
      #endregion
    

下一個步驟將為您示範如何將資料列加入 Power BI 資料表The next step shows you how to add rows to a Power BI table.

以下是完整程式碼清單Below is the complete code listing.

完整程式碼清單Complete code listing

using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace walkthrough_push_data
{
    class Program
    {
        private static string token = string.Empty;

        static void Main(string[] args)
        {

            //Get an authentication access token
            token = GetToken();

            //Create a dataset in Power BI
            CreateDataset();

            //Get a dataset to add rows into a Power BI table
            string datasetId = GetDataset();

        }

        #region Get an authentication access token
        private static string GetToken()
        {
            // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
            // and add using Microsoft.IdentityModel.Clients.ActiveDirectory

            //The client id that Azure AD created when you registered your client app.
            string clientID = "{Client_ID}";

            //RedirectUri you used when you register your app.
            //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
            // You can use this redirect uri for your client app
            string redirectUri = "https://login.live.com/oauth20_desktop.srf";

            //Resource Uri for Power BI API
            string resourceUri = "https://analysis.windows.net/powerbi/api";

            //OAuth2 authority Uri
            string authorityUri = "https://login.windows.net/common/oauth2/authorize";

            //Get access token:
            // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
            // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
            // To install the Active Directory Authentication Library NuGet package in Visual Studio,
            //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.

            // AcquireToken will acquire an Azure access token
            // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
            AuthenticationContext authContext = new AuthenticationContext(authorityUri);
            string token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken;

            Console.WriteLine(token);
            Console.ReadLine();

            return token;
        }

        #endregion

        #region Create a dataset in Power BI
        private static void CreateDataset()
        {
            //TODO: Add using System.Net and using System.IO

            string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";
            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets
            HttpWebRequest request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //Create dataset JSON for POST request
            string datasetJson = "{\"name\": \"SalesMarketing\", \"tables\": " +
                "[{\"name\": \"Product\", \"columns\": " +
                "[{ \"name\": \"ProductID\", \"dataType\": \"Int64\"}, " +
                "{ \"name\": \"Name\", \"dataType\": \"string\"}, " +
                "{ \"name\": \"Category\", \"dataType\": \"string\"}," +
                "{ \"name\": \"IsCompete\", \"dataType\": \"bool\"}," +
                "{ \"name\": \"ManufacturedOn\", \"dataType\": \"DateTime\"}" +
                "]}]}";

            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(datasetJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);

                var response = (HttpWebResponse)request.GetResponse();

                Console.WriteLine(string.Format("Dataset {0}", response.StatusCode.ToString()));

                Console.ReadLine();
            }
        }
        #endregion

        #region Get a dataset to add rows into a Power BI table
        private static string GetDataset()
        {
            string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";
            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets
            HttpWebRequest request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "GET";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            string datasetId = string.Empty;
            //Get HttpWebResponse from GET request
            using (HttpWebResponse httpResponse = request.GetResponse() as System.Net.HttpWebResponse)
            {
                //Get StreamReader that holds the response stream
                using (StreamReader reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
                {
                    string responseContent = reader.ReadToEnd();

                    //TODO: Install NuGet Newtonsoft.Json package: Install-Package Newtonsoft.Json
                    //and add using Newtonsoft.Json
                    var results = JsonConvert.DeserializeObject<dynamic>(responseContent);

                    //Get the first id
                    datasetId = results["value"][0]["id"];

                    Console.WriteLine(String.Format("Dataset ID: {0}", datasetId));
                    Console.ReadLine();

                    return datasetId;
                }
            }
        }
        #endregion
    }
}

下一步 >Next Step >

後續步驟Next steps

將資料列新增至 Power BI 資料表Add rows to a Power BI table
Newtonsoft.JsonNewtonsoft.Json
取得資料集Get Datasets
將資料推送至 Power BIPush data into Power BI
Power BI REST API 概觀Overview of Power BI REST API
Power BI REST API 參考Power BI REST API reference

有其他問題嗎?More questions? 試試 Power BI 社群Try the Power BI Community