步驟 3:在 Power BI 中建立資料集Step 3: Create a dataset in Power BI

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

在將資料推送至資料集的步驟 2 取得驗證存取權杖中,您取得了向 Azure AD 驗證的權杖。In step 2 of Push data into a dataset, Get an authentication access token, you got a token to authenticate to Azure AD. 在此步驟中,您會使用權杖來呼叫建立資料集作業。In this step, you use the token to call the Create Dataset operation.

若要呼叫 REST 資源,您可使用用以定位資源的 URL,以及將 JavaScript 物件標記法 (JSON) 字串 (其中描述資料集) 傳送到 Power BI 服務資源。To make a call to a REST resource, you use a url that locates the resource, and you send a JavaScript Object Notation (JSON) string, which describes the dataset, to the Power BI service resource. REST 資源會識別您想要使用的 Power BI 服務之部分。A REST resource identifies the part of the Power BI service you want to work with. 若要將資料推送至資料集,則目標資源是資料集To push data into the dataset, the target resource is a Dataset. 識別資料集的 URL 是 https://api.PowerBI.com/v1.0/myorg/datasets。The URL that identifies a dataset is https://api.PowerBI.com/v1.0/myorg/datasets. 若您正在將資料推送至群組中,則 URL 會是 https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets。If you are pushing data within a group, the url is https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets.

若要驗證 Power BI REST 作業,您可將在取得驗證存取權杖中取得的權杖加入要求標頭:To authenticate a Power BI REST operation, you add the token you got in Get an authentication access token to a request header:

當您呼叫建立資料集作業時,會建立新的資料集。When you call the Create Dataset operation, a new dataset is created.

以下是在 Power BI 中建立資料集的方法。Here's how to create a dataset in Power BI.

在 Power BI 中建立資料集Create a dataset in Power BI

注意

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

  1. 步驟 2 - 取得驗證存取權杖所建立的主控台應用程式專案中,將 using System.Net;using System.IO; 加入 Program.cs。In the Console Application project you created in Step 2 - Get an authentication access token, add using System.Net;, and using System.IO; to Program.cs.
  2. 在 Program.cs 中,加入下列程式碼。In Program.cs, add the code below.
  3. 執行主控台應用程式,然後登入您的 Power BI 帳戶。Run the Console App, and login to your Power BI account. 您應該會在主控台視窗中看到 建立的資料列You should see Dataset Created in the Console Window. 此外,您可以登入 Power BI,以查看新的資料集。Also, you can login to Power BI to see the new dataset.

將資料推送至資料集的範例Sample push data into 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();
    }
    
  • 加入 CreateDataset() 方法:Add a CreateDataset() method:

    #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
    

下一個步驟將為您示範如何取得資料集,以將資料列加入 Power BI 資料表The next step shows you how to get a dataset to add rows into 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;

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();

        }

        #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
    }
}

下一步 >Next Step >

後續步驟Next steps

取得資料集,以便將資料列新增至 Power BI 資料表Get a dataset to add rows into a Power BI table
取得驗證存取權杖Get an authentication access token
建立資料集Create Dataset
將資料推送至 Power BI 儀表板Push data into a Power BI Dashboard
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