首頁 > web前端 > js教程 > 主體

有效視覺化資料:在 JavaScript 資料透視欄位清單中新增網格和圖表

王林
發布: 2024-09-10 11:04:53
原創
1035 人瀏覽過

TL;DR:讓我們看看如何使用伺服器端引擎將網格和圖表新增至 JavaScript 資料透視表的欄位清單。我們將介紹如何設定 Web API、將資料透視欄位清單連接到 API,以及傳遞輸入資料以呈現網格和圖表。本部落格也示範如何根據使用者互動動態過濾和更新元件,以實現即時數據視覺化。

JavaScript 資料透視欄位清單是一個功能強大的元件,其運作方式與 Microsoft Excel 類似。它允許您新增或刪除欄位並在不同的軸上重新排列它們,例如列、行、值和篩選器。排序和過濾選項也可以在運行時動態套用。

在本部落格中,我們將看到使用 JavaScript 資料透視表的欄位清單元件和伺服器端引擎建立表格和圖表的詳細步驟。在這裡,我們不會使用資料透視表中內建的網格和圖表功能。相反,我們將添加 Syncfusion JavaScript DataGrid 和圖表元件來有效地視覺化資料。

為此,我們需要使用伺服器端引擎建立一個欄位清單。

什麼是伺服器端引擎?

伺服器端引擎可以直接連接到您的資料來源,收集原始輸入數據,並根據 JavaScript 資料透視表透過 UI 互動提供的報告在內部定期執行所有面向資料透視表的計算。然後,它僅將資料透視表或資料透視圖的聚合資料傳輸到客戶端(瀏覽器)。

注意:有關更多詳細信息,請參閱 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 Gallery 安裝 Syncfusion.Pivot.Engine NuGet 套件,如下圖所示。

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

步驟 3:設定 Web API 控制器

要呈現資料透視表欄位列表,請將以下程式碼分別加入伺服器端的 PivotController.csProgram.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;
            }
        }
    }
}
登入後複製

[Program.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/post 對應到 index.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 Pivot Field List 中綁定的報表,我們可以從資料庫中檢索資料並將其傳回給客戶端。

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!

Blogs connexes

  • Créez facilement des diagrammes de planificateur d'étage interactifs à l'aide de la bibliothèque de diagrammes JavaScript
  • Synchronisez sans effort les contrôles JavaScript à l'aide de DataManager
  • Optimiser la productivité : intégrer Salesforce avec JavaScript Scheduler
  • Optimiser la gestion de la mémoire dans le tableau croisé dynamique JavaScript : bonnes pratiques et astuces

以上是有效視覺化資料:在 JavaScript 資料透視欄位清單中新增網格和圖表的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板