热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PivotingDataTableSimplified

Downloadsourcefile(C#)-1.6KBDownloaddemo-14.4KBDownloadsource[VB.NET]-1.98KBDownloaddemo

 




  • Download
    source file (C#) - 1.6 KB

  • Download
    demo - 14.4 KB

  • Download
    source [VB.NET] - 1.98 KB

  • Download
    demo [VB.NET] - 15 KB

Introduction

Displaying data in tabular form is an essential part of any application
nowadays. But sometimes you need to display a huge amount of data in terms of
number of rows. It becomes very difficult to analyse if the number of rows is
huge. In such cases, you may wish to summarize your data in the other formats
like charts, graphs, groups, pivots, etc. This article presents a simplified way
to pivot your data with an appropriate aggregate function so that you can
enhance your reports easily. Based on the feedback given by various readers,
more features have been provided to pivot class. The pivot class is now capable
to pivot data on both the axis at a time. Moreover, it also has the facility to
do sub-total column wise.  

Below is a screenshot of pivoted data in a GridView

bubuko.com,布布扣 >


How it Works

To simplify the scenario, I have divided the result table into three areas:
RowField, DataField, and ColumnFields. If
you wish to do pivot on both the axis, you may use another overload of the same
method where you just need to pass RowFields parameter as an array.
Apart from the area, the Pivot class provides you the option to
bind your data based on some aggregate functions. The various aggregate options
available are:



  • Count: Returns the count of matching data

  • Sum: Returns the sum of matching data (to get the sum, the
    type of the DataField must be convertible to decimal type)

  • First: Returns the first occurrence of matching data

  • Last: Returns the last occurrence of matching data

  • Average: Returns the average of matching data (to get the
    average, the type of the DataField must be convertible to decimal
    type)

  • Max: Returns the maximum value from the matching data

  • Min: Returns the minimum value from the matching data

  • Exists: Returns "true" if there is any
    matching data, else "false"

The code mainly contains a class named "Pivot" that takes the
DataTable in the constructor. ColumnFields takes as a
string array parameter which allows you to pivot data on more than one column.
It contains a function called PivotData() which actually pivots
your data.


public DataTable PivotData(string RowField, string DataField,
AggregateFunction Aggregate, params string[] ColumnFields)
{
DataTable dt = new DataTable();
string Separator = ".";
var RowList = (from x in _SourceTable.AsEnumerable()
select new { Name = x.Field<object>(RowField) }).Distinct();
var ColList = (from x in _SourceTable.AsEnumerable()
select new { Name = ColumnFields.Select(n => x.Field<object>(n))
.Aggregate((a, b) => a += Separator + b.ToString()) })
.Distinct()
.OrderBy(m => m.Name);
dt.Columns.Add(RowField);
foreach (var col in ColList)
{
dt.Columns.Add(col.Name.ToString());
}
foreach (var RowName in RowList)
{
DataRow row = dt.NewRow();
row[RowField] = RowName.Name.ToString();
foreach (var col in ColList)
{
string strFilter = RowField + " = ‘" + RowName.Name + "‘";
string[] strColValues =
col.Name.ToString().Split(Separator.ToCharArray(),
StringSplitOptions.None);
for (int i = 0; i strFilter += " and " + ColumnFields[i] +
" = ‘" + strColValues[i] + "‘";
row[col.Name.ToString()] = GetData(strFilter, DataField, Aggregate);
}
dt.Rows.Add(row);
}
return dt;
}

PivotData method also has 2 more overloads. If you wish to show
column wise sub-total, you may use the overload by passing a bool
variable showSubTotal. If you wish to Pivot
your data on both side, i.e., row-wise as well as column-wise, you may wish to
use another overload where you can pass rowFields and
columnFields as an array. 

First of all, the function determines the number of rows by getting the
distinct values in RowList, and the number of columns by getting
the distinct values in ColList. Then, the columns are created. It
then iterates through each row and gets the matching values to the corresponding
cell based on the aggregate function provided. To retrieve the matching value,
the GetData() function is called.


private object GetData(string Filter, string DataField, AggregateFunction Aggregate)
{
try
{
DataRow[] FilteredRows = _SourceTable.Select(Filter);
object[] objList =
FilteredRows.Select(x => x.Field<object>(DataField)).ToArray();
switch (Aggregate)
{
case AggregateFunction.Average:
return GetAverage(objList);
case AggregateFunction.Count:
return objList.Count();
case AggregateFunction.Exists:
return (objList.Count() == 0) ? "False" : "True";
case AggregateFunction.First:
return GetFirst(objList);
case AggregateFunction.Last:
return GetLast(objList);
case AggregateFunction.Max:
return GetMax(objList);
case AggregateFunction.Min:
return GetMin(objList);
case AggregateFunction.Sum:
return GetSum(objList);
default:
return null;
}
}
catch (Exception ex)
{
return "#Error";
}
return null;
}

This function first filters out the matching RowField and
ColumnFields data in the DataRow[] array and then
applies the aggregate function on it.


Using the Code

Using the code is simple. Create an instance of the Pivot class
and then call the PivotData method with the required parameters.
The PivotData() method returns the DataTable which can
directly be used as the DataSource of the
GridView


DataTable dt = ExcelLayer.GetDataTable("_Data\\DataForPivot.xls", "Sheet1$");
Pivot pvt = new Pivot(dt);
grdPivot.DataSource = pvt.PivotData("Designation", "CTC",
AggregateFunction.Max, "Company", "Department", "Year");
grdPivot.DataBind();

The database used as a sample is an Excel sheet and is present in the
"_Data" folder of the root folder of sample application.


Merge GridView Header Cells

The MergeHeader function is created to merge the header cells to
provide a simplified look.


private void MergeHeader(GridView gv, GridViewRow row, int PivotLevel)
{
for (int iCount = 1; iCount <= PivotLevel; iCount++)
{
GridViewRow oGridViewRow = new GridViewRow(0, 0,
DataControlRowType.Header, DataControlRowState.Insert);
var Header = (row.Cells.Cast()
.Select(x => GetHeaderText(x.Text, iCount, PivotLevel)))
.GroupBy(x => x);
foreach (var v in Header)
{
TableHeaderCell cell = new TableHeaderCell();
cell.Text = v.Key.Substring(v.Key.LastIndexOf(_Separator) + 1);
cell.ColumnSpan = v.Count();
oGridViewRow.Cells.Add(cell);
}
gv.Controls[0].Controls.AddAt(row.RowIndex, oGridViewRow);
}
row.Visible = false;
}

The function creates a new row for each pivot level and merges accordingly.
PivotLevel here is the number of columns on which the pivot is
done.

Header gets all the column values in an array, groups the
repeated values returned by the GetHeaderText() function, sets the
ColumnSpan property of the newly created cell according to the
number of repeated HeaderText, and then adds the cell to the
GridViewRow. Finally, add the GridViewRow to the
GridView.

The GetHeaderText() function returns the header text based on
the PivotLevel.

For example, suppose a pivot is done on three ColumnFields,
namely, Company, Department, and Year. The result header of the
GridView will initially have a header like Company.Department.Year
for a PivotLevel 1. GetHeaderText() will return
Company. For a PivotLevel 2, GetHeaderText() will
return Company.Department. For a PivotLevel 3,
GetHeaderText() will return Company.Department.Year, and so
on... 


Merge GridView Row Header Cells

This may needs to be done when you are pivoting your data row-wise also. Here
we are simply merging the cells with same text.


private void MergeRows(GridView gv, int rowPivotLevel)
{
for (int rowIndex = gv.Rows.Count - 2; rowIndex >= 0; rowIndex--)
{
GridViewRow row = gv.Rows[rowIndex];
GridViewRow prevRow = gv.Rows[rowIndex + 1];
for (int colIndex = 0; colIndex {
if (row.Cells[colIndex].Text == prevRow.Cells[colIndex].Text)
{
row.Cells[colIndex].RowSpan = (prevRow.Cells[colIndex].RowSpan <2) ? 2 : prevRow.Cells[colIndex].RowSpan + 1;
prevRow.Cells[colIndex].Visible = false;
}
}
}
}

The code to merge header rows is fairly simple. It simply loops through all
the row header cells from bottom to top, compare the text with previous
corresponding row cell, increases the row span by 1 if same and hide the
previous corresponding row.

Screen shot for both side pivot:

bubuko.com,布布扣

Below is the screenshot of the GridView containing the third
level pivoted data:

bubuko.com,布布扣 >


Points of Interest

Along with pivoting the DataTable, the code will also help you
to merge the header cells in the desired format in GridView.
Moreover, you may have a deeper look into PivotData method to know
how you can search or filter data in DataTable suing linq. Apart from this,
MergeRows method acts as a sample to merge rows in a GridView. For
beginners, the ExcelLayer.GetDataTable() method will be a sample to
get the data from the Excel Sheet.

You may also wish to consider the following link to pivot a
DataTable: http://www.codeproject.com/KB/recipes/CsharpPivotTable.aspx.


Future Consideration

Currently, the code can pivot data only for a DataTable. The
code will be enhanced to pivot any object derived from an
IListSource or ICollection.

Pivoting DataTable Simplified,布布扣,bubuko.com


推荐阅读
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • GetWindowLong函数
    今天在看一个代码里头写了GetWindowLong(hwnd,0),我当时就有点费解,靠,上网搜索函数原型说明,死活找不到第 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • [译]技术公司十年经验的职场生涯回顾
    本文是一位在技术公司工作十年的职场人士对自己职业生涯的总结回顾。她的职业规划与众不同,令人深思又有趣。其中涉及到的内容有机器学习、创新创业以及引用了女性主义者在TED演讲中的部分讲义。文章表达了对职业生涯的愿望和希望,认为人类有能力不断改善自己。 ... [详细]
author-avatar
大爱开心一下吧_616
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有