효과적인 데이터 시각화: JavaScript 피벗 필드 목록에 그리드 및 차트 추가

王林
풀어 주다: 2024-09-10 11:04:53
원래의
995명이 탐색했습니다.

TL;DR:서버측 엔진을 사용하여 JavaScript 피벗 테이블의 필드 목록에 그리드와 차트를 추가하는 방법을 살펴보겠습니다. 웹 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단계: 웹 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 속성을 사용하여 호스팅된 웹 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');
로그인 후 복사

위 코드를 실행하면 아래 이미지와 같이 Pivot Field List가 나타납니다.

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!

Related blogs

  • Easily Create Interactive Floor Planner Diagrams Using JavaScript Diagram Library
  • Effortlessly Synchronize JavaScript Controls Using DataManager
  • Optimizing Productivity: Integrate Salesforce with JavaScript Scheduler
  • Optimize Memory Management in JavaScript Pivot Table: Best Practices and Tips

위 내용은 효과적인 데이터 시각화: JavaScript 피벗 필드 목록에 그리드 및 차트 추가의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!