データを効果的に視覚化する: JavaScript ピボット フィールド リストにグリッドとグラフを追加する

王林
リリース: 2024-09-10 11:04:53
オリジナル
994 人が閲覧しました

TL;DR:サーバー側エンジンを使用して、JavaScript ピボット テーブルのフィールド リストにグリッドとグラフを追加する方法を見てみましょう。 Web API の設定、ピボット フィールド リストの API への接続、入力データを渡してグリッドとチャートをレンダリングする方法について説明します。このブログでは、リアルタイム データ視覚化のためにユーザー インタラクションに基づいてコンポーネントを動的にフィルタリングおよび更新する方法も示します。

JavaScript ピボット フィールド リストは、Microsoft Excel と同様に機能する強力なコンポーネントです。これにより、フィールドを追加または削除したり、列、行、値、フィルターなどのさまざまな軸にわたってフィールドを再配置したりできます。並べ替えとフィルターのオプションは、実行時に動的に適用することもできます。

このブログでは、サーバー側エンジンで JavaScript ピボット テーブルのフィールド リスト コンポーネントを使用してグリッドとチャートを作成する詳細な手順を説明します。ここでは、ピボット テーブルの組み込みのグリッドとグラフの機能は使用しません。代わりに、Syncfusion JavaScript DataGrid コンポーネントと Charts コンポーネントを追加して、データを効果的に視覚化します。

これを行うには、サーバー側エンジンを使用してフィールド リストを作成する必要があります。

サーバーサイドエンジンとは何ですか?

サーバー側エンジンは、データ ソースに直接接続し、生の入力データを収集し、UI インタラクションを通じて JavaScript ピボット テーブルによって提供されるレポートに基づいて、すべてのピボット指向の計算を内部で定期的に実行できます。その後、ピボット テーブルまたはピボット チャートの集計データのみをクライアント側 (ブラウザー) に送信します。

注:詳細については、JavaScript ピボット テーブルのドキュメントのサーバー側エンジンの実装を参照してください。

ASP.NET Core アプリでピボット フィールド リストを構築する手順

ASP.NET Core アプリでピボット フィールド リストを作成するには、次の手順に従います。

ステップ 1: WebAPI コントローラーの作成

まず、Visual Studio を開いて空の ASP.NET Core アプリを作成します。以下の画像を参照してください。

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

次に、空の WebAPI コントローラーを作成し、PivotController という名前を付けます。以下の画像を参照してください。

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

ステップ 2: Syncfusion.Pivot.Engine NuGet パッケージをインストールする

サーバー側エンジンを使用するには、次の図に示すように、NuGet ギャラリーから Syncfusion.Pivot.Engine NuGet パッケージをインストールします。

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

ステップ 3: Web API コントローラーの構成

ピボット フィールド リストをレンダリングするには、サーバー側の PivotController.cs および Program.cs ファイルにそれぞれ次のコードを追加します。

PivotController で、表示されるフィールドを含む GetPivotValues メソッドの PivotEngine.Data プロパティに空のデータを割り当てます。ピボット フィールド リストで。 コレクション、JSON、CSV、DataTable、、または 動的データ ソースを使用してフィールドを生成できます。ここでは、ExpandoObject (動的) を使用してデータを割り当てました。

[PivotController.cs]

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Syncfusion.Pivot.Engine;
using System.Diagnostics.Metrics;
using System.Dynamic;

namespace PivotController.Controllers
{
    [Route("api/[controller]")]
    public class PivotController : Controller
    {
        private PivotEngine<ExpandoObject> PivotEngine = new PivotEngine<ExpandoObject>();

        [Route("/api/pivot/post")]
        [HttpPost]
        public async Task<object> Post([FromBody] object args)
        {
            FetchData param = JsonConvert.DeserializeObject<FetchData>(args.ToString());
            if (param.Action == "fetchFieldMembers")
            {
                return await GetMembers(param);
            }
            else
            {
                return await GetPivotValues(param);
            }
        }

        private async Task<object> GetMembers(FetchData param)
        {
            Dictionary<string, object> returnValue = new Dictionary<string, object>();
            if (param.MemberName == "Year")
            {
                returnValue["memberName"] = param.MemberName;
                Dictionary<string, Members> result = new Dictionary<string, Members>();
                result.Add("FY 2005", new Members()
                {
                    Caption = "FY 2005",
                    Name = "FY 2005",
                    IsSelected = true
                });
                result.Add("FY 2006", new Members()
                {
                    Caption = "FY 2006",
                    Name = "FY 2006",
                    IsSelected = true
                });
                result.Add("FY 2007", new Members()
                {
                    Caption = "FY 2007",
                    Name = "FY 2007",
                    IsSelected = false
                });
                result.Add("FY 2008", new Members()
                {
                    Caption = "FY 2008",
                    Name = "FY 2008",
                    IsSelected = false
                });
                returnValue["members"] = JsonConvert.SerializeObject(result);
            }
            return returnValue;
        }

        private async Task<object> GetPivotValues(FetchData param)
        {
            List<ExpandoObject> listData = new List<ExpandoObject>();
            dynamic d = new ExpandoObject();
            d.ProductID = "";
            d.Year = "";
            d.Country = "";
            d.Product = "";
            d.Price = 0;
            d.Sold = 0;
            listData.Add(d);
            PivotEngine.Data = listData;
            EngineProperties engine = await PivotEngine.GetEngine(param);
            Dictionary<string, object> result = PivotEngine.GetSerializedPivotValues();
            result["pivotCount"] = "";
            result["pivotValue"] = "";
            result["data"] = new PivotViewData().GetVirtualData(1000, param);
            return result;
        }

        public class PivotViewData
        {
            public string ProductID { get; set; }
            public string Country { get; set; }
            public string Product { get; set; }
            public double Sold { get; set; }
            public double Price { get; set; }
            public string Year { get; set; }

            public List<PivotViewData> GetVirtualData(int count, FetchData param)
            {
                List<PivotViewData> VirtualData = new List<PivotViewData>();

                for (int i = 1; i <= count; i++)
                {
                    PivotViewData p = new PivotViewData
                    {
                        ProductID = "PRO-" + (count + i),
                        Year = param.Action == "onFilter" ? param.FilterItem.Items[new Random().Next(param.FilterItem.Items.Length)] : (new string[] { "FY 2015", "FY 2016", "FY 2017", "FY 2018", "FY 2019" })[new Random().Next(5)],
                        Country = (new string[] { "Canada", "France", "Australia", "Germany", "France" })[new Random().Next(5)],
                        Product = (new string[] { "Car", "Van", "Bike", "Flight", "Bus" })[new Random().Next(5)],
                        Price = (3.4 * i) + 500,
                        Sold = (i * 15) + 10
                    };
                    VirtualData.Add(p);
                }
                return VirtualData;
            }
        }
    }
}
ログイン後にコピー

[プログラム.cs]

var builder = WebApplication.CreateBuilder(args);
var CustomOrigins = "_customOrigins";

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddCors(options =>
{
    options.AddPolicy(CustomOrigins,
    builder =>
    {
        builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
    });
});

var app = builder.Build();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();
app.UseCors(CustomOrigins);
app.Run();
ログイン後にコピー

コードが更新されたら、IIS でアプリを実行します。 https://localhost:44372/api/pivot/post からアクセスできます。

ステップ 4: JavaScript ピボット フィールド リストを WebAPI コントローラーに接続する

サーバー側エンジンを JavaScript ピボット フィールド リストに接続するには、単純なスタンドアロン JavaScript ピボット フィールドを作成します。 dataSourceSettings の url プロパティを使用して、ホストされた Web API の URL https://localhost:44372/api/pivot/postindex.js ファイルのピボット テーブルにマップします。

次のコード例を参照してください。

[pivot.js]

var fieldlistObj = new ej.pivotview.PivotFieldList({
    dataSourceSettings: {
       // Here, we need to use the service URL.
        url: 'https://localhost:44372/api/pivot/post',
        mode: 'Server',
        type: 'JSON',
        allowMemberFilter: true,
        rows: [{ name: 'Year' }],
        values: [{ name: 'Sold', caption: 'Units Sold' }],
        fieldMapping: [
            { name: 'Sold', type: 'Sum' },
            { name: 'Price', type: 'Sum' },
        ],
    },
    renderMode: 'Fixed',
});
fieldlistObj.appendTo('#PivotFieldList');
ログイン後にコピー

上記のコードを実行すると、次の画像に示すように、ピボット フィールド リストが表示されます。

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

JavaScript ピボット フィールド リストを WebAPI コントローラーに接続します

ステップ 5: 入力データを JavaScript ピボット フィールド リストに渡す

JavaScript ピボット フィールド リストにバインドしたレポートに基づいて、データベースからデータを取得し、クライアントに返すことができます。

For example, we used the PivotViewDataclass to create a sample list (Collection) data source and returned it to the client through the GetPivotValues()method.

The data can be retrieved by calling the Pivot Field List’s afterServiceInvoke event. Then, the Grid and Chartcomponents can be rendered with the data obtained from that event.

Refer to the following code example to render the DataGrid and Charts components based on the input data in the JavaScript Pivot Field List.

[pivot.js]

var fieldlistObj = new ej.pivotview.PivotFieldList({
    dataSourceSettings: {
        url: 'https://localhost:44372/api/pivot/post',
        mode: 'Server',
        type: 'JSON',
        allowMemberFilter: true,
        rows: [{ name: 'Year' }],
        values: [{ name: 'Sold', caption: 'Units Sold' }],
        fieldMapping: [
            { name: 'Sold', type: 'Sum' },
            { name: 'Price', type: 'Sum' },
        ],
    },
    renderMode: 'Fixed',
    afterServiceInvoke: function (args) {
        if (args.action != "fetchFieldMembers") {
            data = JSON.parse(args.response).data;
            grid.dataSource = data;
            grid.columns = getColumns();
            chart.series[0].dataSource = data;
        }
    }
});
fieldlistObj.appendTo('#PivotFieldList');

var grid = new ej.grids.Grid({
    allowSelection: true,
    allowFiltering: true,
    allowSorting: true,
    filterSettings: { type: 'Menu' },
    selectionSettings: {
        persistSelection: true,
        type: 'Multiple',
        checkboxOnly: true,
    },
    enableHover: false,
    enableHeaderFocus: true,
    height: 250
});
grid.appendTo('#Grid');

var chart = new ej.charts.Chart({
    primaryXAxis: {
        valueType: 'Category',
        labelRotation: 90,
        zoomFactor: 0.1
    },
    chartArea: { border: { width: 0 } },
    primaryYAxis: {
        title: 'Units Sold'
    },
    series: [
        {
            type: 'Column',
            xName: 'productID',
            width: 2,
            yName: 'sold',
            name: 'Sales',
        },
    ],
    zoomSettings: {
        enableScrollbar: true
    },
    title: 'Sales Analysis',
    width: '100%',
    tooltip: { enable: true, shared: true },
    legendSettings: { enableHighlight: true },
});
chart.appendTo('#Chart');

function getColumns() {
    var report = {};
    report[0] = fieldlistObj.dataSourceSettings.rows;
    report[1] = fieldlistObj.dataSourceSettings.columns;
    report[2] = fieldlistObj.dataSourceSettings.values;
    report[3] = fieldlistObj.dataSourceSettings.filters;
    var pos = 0;
    var columns = [];
    while (pos < 4) {
        if (report[pos]) {
            for (var cnt = 0; cnt < report[pos].length; cnt++) {
                var field = report[pos][cnt];
                var column = {
                    field: field.name,
                    headerText: field.caption ? field.caption : field.name,
                    width: 150,
                    textAlign: 'Center',
                };
                columns.push(column);
            }
        }
        pos++;
    }
    return columns;
}
ログイン後にコピー

Refer to the following output image.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Creating the Grid and Chart based on the input provided in the JavaScript Pivot Field List

How does the server-side engine work?

Every action in the JavaScript Pivot Field List, such as adding or removing fields, rearranging them across different axes, including columns, rows, values, and filters, and dynamically sorting and filtering options, sends an updated report to the server at runtime. Based on that, we can retrieve data from the database and return it to the client side, enabling us to refresh both Grid and Chart components with the new data.

Updating the Grid and Chart with filtered data

Let’s walk through how to update the Grid and Chart by filtering the field list. When we click the filter icon in a field to which we’ve bound the data source, the server ( PivotController) receives a request with the action name fetchFieldMembersand the name of the specified field. Based on that, we can use the GetMemebers()method to pass the members to the filter dialog.

Refer to the following code example to know how the server-side engine handles this filtering process.

[PivotController.cs]

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Syncfusion.Pivot.Engine;
using System.Diagnostics.Metrics;
using System.Dynamic;

namespace PivotController.Controllers
{
    [Route("api/[controller]")]
    public class PivotController : Controller
    {
        private PivotEngine<ExpandoObject> PivotEngine = new PivotEngine<ExpandoObject>();

        [Route("/api/pivot/post")]
        [HttpPost]
        public async Task<object> Post([FromBody] object args)
        {
            FetchData param = JsonConvert.DeserializeObject<FetchData>(args.ToString());
            if (param.Action == "fetchFieldMembers")
            {
                return await GetMembers(param);
            }
            else
            {
                return await GetPivotValues(param);
            }
        }

        private async Task<object> GetMembers(FetchData param)
        {
            Dictionary<string, object> returnValue = new Dictionary<string, object>();
            if (param.MemberName == "Year")
            {
                returnValue["memberName"] = param.MemberName;
                Dictionary<string, Members> result = new Dictionary<string, Members>();
                result.Add("FY 2015", new Members()
                {
                    Caption = "FY 2015",
                    Name = "FY 2015",
                    IsSelected = true
                });
                result.Add("FY 2016", new Members()
                {
                    Caption = "FY 2016",
                    Name = "FY 2016",
                    IsSelected = true
                });
                result.Add("FY 2017", new Members()
                {
                    Caption = "FY 2017",
                    Name = "FY 2017",
                    IsSelected = true
                });
                result.Add("FY 2018", new Members()
                {
                    Caption = "FY 2018",
                    Name = "FY 2018",
                    IsSelected = true
                });
                returnValue["members"] = JsonConvert.SerializeObject(result);
            }
            return returnValue;
        }
}
ログイン後にコピー

After executing the above code, the members will be displayed in the filter dialog, as shown in the following image.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Displaying filter members in the JavaScript Pivot Field List

The members can then be filtered using the filter dialog. The filtered members are sent to the server along with their field names. Based on the filtered members, we can fetch data from the database and return it to the client to refresh the Grid and Chart components.

For example, we have filtered the Yearfield, as shown in the following image.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Filtering data via the filter dialog in JavaScript Pivot Field List

The filtered members FY 2015and FY 2018will be sent to the server, along with the field name Year. So, we can use that information to filter and retrieve data from the database via the afterServiceInvokeevent, which we can then return to the client to refresh the Grid and Chart components.

Once the filtered data from the database has been assigned to them, the grid and chart will look like this.

Effectively Visualize Data: Add Grids and Charts in JavaScript Pivot Field List

Updating the Grid and Chart in the JavaScript Pivot Field List with the filtered data

GitHub reference

For more details, check out the Adding Grids and Charts in JavaScript Pivot Field List GitHub demo.

Conclusion

Thanks for reading! In this blog, we’ve seen how to add the DataGrid and Charts component to the JavaScript Pivot Table’s Field List to effectively visualize data. This approach can also be used to integrate Syncfusion’s other JavaScript data visualization components. Follow the steps outlined in this blog, and let us know your thoughts in the comments!

For existing customers, the latest version of Essential Studio can be downloaded from the License and Downloads page. If you are new to Syncfusion, try our 30-day free trial to check out the available features.

For any questions, you can contact us through our support forum, support portal, or feedback portal. We are always happy to assist you!

Verwandte Blogs

  • Erstellen Sie ganz einfach interaktive Grundrissdiagramme mithilfe der JavaScript-Diagrammbibliothek
  • JavaScript-Steuerelemente mühelos mit DataManager synchronisieren
  • Produktivität optimieren: Salesforce mit JavaScript Scheduler integrieren
  • Speicherverwaltung in der JavaScript-Pivot-Tabelle optimieren: Best Practices und Tipps

以上がデータを効果的に視覚化する: JavaScript ピボット フィールド リストにグリッドとグラフを追加するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!