TL;DR:讓我們看看如何使用伺服器端引擎將網格和圖表新增至 JavaScript 資料透視表的欄位清單。我們將介紹如何設定 Web API、將資料透視欄位清單連接到 API,以及傳遞輸入資料以呈現網格和圖表。本部落格也示範如何根據使用者互動動態過濾和更新元件,以實現即時數據視覺化。
JavaScript 資料透視欄位清單是一個功能強大的元件,其運作方式與 Microsoft Excel 類似。它允許您新增或刪除欄位並在不同的軸上重新排列它們,例如列、行、值和篩選器。排序和過濾選項也可以在運行時動態套用。
在本部落格中,我們將看到使用 JavaScript 資料透視表的欄位清單元件和伺服器端引擎建立表格和圖表的詳細步驟。在這裡,我們不會使用資料透視表中內建的網格和圖表功能。相反,我們將添加 Syncfusion JavaScript DataGrid 和圖表元件來有效地視覺化資料。
為此,我們需要使用伺服器端引擎建立一個欄位清單。
伺服器端引擎可以直接連接到您的資料來源,收集原始輸入數據,並根據 JavaScript 資料透視表透過 UI 互動提供的報告在內部定期執行所有面向資料透視表的計算。然後,它僅將資料透視表或資料透視圖的聚合資料傳輸到客戶端(瀏覽器)。
注意:有關更多詳細信息,請參閱 JavaScript 資料透視表文件中實作伺服器端引擎。
依照以下步驟在 ASP.NET Core 應用程式中建立資料透視欄位清單:
先開啟 Visual Studio 並建立一個空的 ASP.NET Core 應用程式。請參考下圖。
然後,建立一個空的 WebAPI 控制器並將其命名為 PivotController。請參考下圖。
要使用伺服器端引擎,請從 NuGet Gallery 安裝 Syncfusion.Pivot.Engine NuGet 套件,如下圖所示。
要呈現資料透視表欄位列表,請將以下程式碼分別加入伺服器端的 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; } } } }
[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 存取它。
要將伺服器端引擎連接到 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');
執行上述程式碼後,將出現透視欄位列表,如下圖所示。
根據我們在 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.
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.
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.
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.
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.
For more details, check out the Adding Grids and Charts in JavaScript Pivot Field List GitHub demo.
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!
以上是有效視覺化資料:在 JavaScript 資料透視欄位清單中新增網格和圖表的詳細內容。更多資訊請關注PHP中文網其他相關文章!