我正在使用NReco库来构建数据透视表。我正在关注这些示例,并且我能够从DataSet构建一个简单的PvT。现在我想要构建一个PvT,它接收在运行时选择的一些度量,但是我在使用一个度量列表的过程的动态性质上遇到了麻烦,每个度量列表都有自己的聚合公式。该公式在运行时是已知的,它只不过是总和或平均值,而是特定于度量。我有以下代码:
private string CreatePivotTable(DataTable dt, string[] lines, string[] columns, string[] dimensions, string measure)
{
var pivotData = new PivotData(dimensions, new SumAggregatorFactory(measure), new DataTableReader(dt));
var pivotTable = new PivotTable(lines, columns, pivotData);
var htmlResult = new StringWriter();
var pvtHtmlWr = new PivotTableHtmlWriter(htmlResult);
pvtHtmlWr.Write(pivotTable);
return htmlResult.ToString();
}
我想做以下代码,以便在运行时动态添加度量和聚合器:
private string CreatePivotTable(DataTable dt, string[] lines, string[] columns, string[] dimensions, Measure[] measures)
{
var pivotData = new PivotData(dimensions, null, new DataTableReader(dt));
foreach(var m in measures)
{
if (m.Formula.equals("sum"))
pivotData.AggregatorFactory.Create(new SumAggregator(m.ColName));
else if(m.Formula.equals("avg")){
pivotData.AggregatorFactory.Create(new AvgAggregator(m.ColName));
}
}
}
我怎样才能实现这样的目标?有办法吗?
答案 0 :(得分:0)
您可以配置PivotData
类以按以下方式收集多个度量:
private string CreatePivotTable(
DataTable dt, string[] lines, string[] columns, string[] dimensions, Measure[] measures)
{
var aggrFactories = new List<IAggregatorFactory>();
foreach(var m in measures) {
if (m.Formula.equals("sum"))
aggrFactories.Add( new SumAggregatorFactory(m.ColName));
else if(m.Formula.equals("avg")){
aggrFactories.Add( new AverageAggregatorFactory(m.ColName));
}
}
if (aggrFactories.Length==0) {
// no measures provided.
// Throw an exception or configure "default" measure (say, CountAggregatorFactory)
aggrFactories.Add( new CountAggregatorFactory() );
}
var pivotData = new PivotData(dimensions,
aggrFactories.Length==1 ? aggrFactories[0] : new CompositeAggregatorFactory(aggrFactories.ToArray()),
new DataTableReader(dt));
// you code that renders HTML pivot table with PivotTableHtmlWriter
}
作为替代方案,您可以使用可以PivotDataFactory
模型创建PivotData
实例的PivotDataConfiguration
组件(NReco.PivotData.Extensions程序集):
private string CreatePivotTable(DataTable dt, string[] lines, string[] columns, string[] dimensions, Measure[] measures)
{
var pvtDataFactory = new PivotDataFactory();
var pivotData = pvtDataFactory.Create( new PivotDataConfiguration() {
Dimensions = dimensions,
Aggregators = measures
.Select(m => new AggregatorFactoryConfiguration(m.Formula, new[] {m.ColName}) )
.ToArray()
});
// you code that renders HTML pivot table with PivotTableHtmlWriter
}
PivotDataFactory
了解标准聚合器类型(&#34; Count&#34;,&#34; Sum&#34;,&#34; Average&#34;,&#34; Min&#34;, &#34; Max&#34;)如果您使用自定义实现,则可以使用PivotDataFactory.RegisterAggregator
方法注册它们(有关详细信息,请参阅Implement custom aggregator)。
BTW真实的用户定义公式(可以使用聚合器值作为参数)也是可能的:参见&#34; DynamicFormulaMeasure&#34;来自PivotData SDK示例包的示例。