Creating a pivot table report from the code behind

Creating a pivot table report from the code behind

In this tutorial we will learn how to build a report with a Pivot Table from code.

SharpShooter Reports.WPF allows adding code tables (analogically to other products).

Below you can see a code snippet that demonstrates the ability mentioned above:

private void CreateReport()

{

      PerpetuumSoft.Reporting.DOM.Document doc = new PerpetuumSoft.Reporting.DOM.Document();

      doc.Name = "doc1";

      doc.IsTemplate = true;

      doc.ScriptLanguage = PerpetuumSoft.Reporting.DOM.ScriptLanguage.CSharp;

      PerpetuumSoft.Reporting.DOM.Page page = new PerpetuumSoft.Reporting.DOM.Page();

      page.Name = "page1";

      doc.Pages.Add(page);

      PerpetuumSoft.Reporting.DOM.Olap.PivotTable pivotTable = new PerpetuumSoft.Reporting.DOM.Olap.PivotTable();

      pivotTable.Name = "pivotTable1";

      pivotTable.RowHeight = 30;

      pivotTable.DataSource = "Sales";

      pivotTable.Shift = 0;

      pivotTable.Layout.XDimensions.Add

      (new Field

       {

          Caption = "Company Name",

          Expression = "GetData(\"Sales.CompanyName\")"

       }

      );

      pivotTable.Layout.YDimensions.Add

      (new Field

       {

           Caption = "Category Name",

           Expression = "GetData(\"Sales.CategoryName\")"

       }

      );

      pivotTable.Layout.YDimensions.Add

      (new Field

       {

            Caption = "Product Name",

            Expression = "GetData(\"Sales.ProductName\")"

        }

       );

       pivotTable.Layout.Facts.Add

       (new Field

        {

            Caption = "Sales sum",

            TotalLabel = "Total sum",

            ShowTotal = true,

            Width = 150,

            Aggregate = new AggregateFunctionFactory.Sum(),

            Expression = "(double)GetData(\"Sales.UnitPrice\") *(double)GetData(\"Sales.Quantity\") * (1 - (double)GetData(\"Sales.Discount\"))"

         }

       );

       page.Controls.Add(pivotTable);

       ReportSource reportSource = new ReportSource();

       reportSource.DataSources.Add("Sales", _sales);

       string reportText = null;

       using (MemoryStream ms = new MemoryStream())

       {

            PerpetuumSoft.Framework.Serialization.XSerializationManager.Write(doc, ms);

            ms.Position = 0;

            using (StreamReader sr = new StreamReader(ms))

            {

                reportText = sr.ReadToEnd();

            }

        }

        reportSource.Source = reportText;

        reportViewer.Source = reportSource;

        reportViewer.RenderDocument();

 }


And here you can find a full code of the sample:

http://perpetuumsoft.com/Support/SSR.WPF/DynamicPivotSample.zip

Add Feedback