Pivot tables (VB.Net / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\vb\VS2022\netframework\20.Reports\80.Pivot Tables and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/vb/VS2022/netframework/Modules/20.Reports/80.Pivot Tables
Overview
Pivot Tables are a very useful (and complex) Excel feature that allows you to summarize data and see it from different points of view just by clicking on fields.
FlexCel doesn't have support on the API for Pivot tables, but as usual, you can define one on the template, fill in the data as you would in a normal report, and the Pivot Table will be refreshed with it. There are some issues and things you have to take in account to make it work, but it is usually worth it.
Pivot tables work in both xls and xlsx, but FlexCel won't convert between them. A report made from an xls template must be saved as xls, and a report made from an xlsx template must be saved as xlsx for pivot tables to be preserved.
Concepts
Xls Templates: Excel saves a cache data for opening the pivot faster next time, and you can't use this on FlexCel because it is not implemented (FlexCel does not calculate the data in the pivot table). So, in the template, right-click the table, select "Don't save on open", and deselect "Update on open". Note: FlexCel will make this automatically in xlsx templates, so you don't need to do it.
Xls Templates: Defining a Named Range for the table data: The only way to get the Pivot Table range updated as you insert rows, is to define a named range ("TableData" in this example). When asked for the range to the Pivot table, refer to it. Do not select the range directly, or it won't be expanded. Note: This doesn't apply to xlsx templates, in those cases FlexCel will also expand direct ranges and you don't need to use a name, even when it isn't a bad idea anyway.
X ranges again! We need the pivot table range to be 2 rows at least, but we don't want the second row to be on the generated report. Same as in Charts, we use an "X" range that will erase the last row once it is done.
"." Sheets and "_." ranges . As FlexCel by default processes all sheets on the file, we would have a problem because it doesn't find the datasets on the Pivot Table sheet. One way to exclude FlexCel from reading a sheet, prefix its name with a dot "." The dot will be erased from the final sheet name. Here it doesn't work because the name of the sheet changes, and then the pivot chart loses its reference. So, we use a "." range. Ranges starting with a dot ("_.", "__.", "I_." and "II_.") are ignored by FlexCel.
When you insert cells the pivot table won't move. On this example, we included a file on cell A1, but we left the rows empty before inserting the pivot table. In general, the best you can do is to leave the pivot table alone on a sheet, without any <#tags>, and inside a "_." range.
There is a know issue with Excel and Internet explorer if you are doing a web application and trying to open the file directly from ie. When opening the file, ie will save it in a temporary folder with a name like "filename[1].xls" and then open it with Excel. The problem is that Excel does not allow [] characters in a filename, because it uses them in formulas to specify external files. In this case you will get an error and Excel won't update the pivot chart. Note that this is not related in any way to FlexCel, nor we can do anything to solve it. The problem happens with any Excel file with pivot tables that you open directly from ie, and the only solution is to save the file to disk before opening it, or use other browser. You can find more information at: http://www.microsoft.com/office/community/en-us/default.mspx?mid=146e209c-7f5d-4c5c-865c-42cfdb09d79b&dg=microsoft.public.excel.crashesgpfs and http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1398316&SiteID=1
Excel by default does not delete old entries in the comboboxes inside the pivot table, no matter how much you refresh the pivot table. This means that you will see "...delete row..." inside those comboboxes, since those entries were there when you created the template and they won't be deleted. You could get rid of them with a macro, but adding a macro to a sheet will add a security warning, so probably it is not worth it. But there is other undocumented way: If you can get a copy of Excel 2007 or newer to edit the template, you can set the "Pivot Table options", "Data" tab, "Number of items to retain per field" and set it to "none". The good thing about it is that once you change it, it will work also in Excel 2003, even when there is no way to change that option from Excel 2003 user interface.
Files
AssemblyInfo.vb
Imports System.Reflection
Imports System.Runtime.CompilerServices
'
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
'
<Assembly: AssemblyTitle("")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyConfiguration("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("")>
<Assembly: AssemblyCopyright("(c) 2002 - 2014 TMS Software")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyCulture("")>
'
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Revision and Build Numbers
' by using the '*' as shown below:
<Assembly: AssemblyVersion("6.2.1.0")>
'
' In order to sign your assembly you must specify a key to use. Refer to the
' Microsoft .NET Framework documentation for more information on assembly signing.
'
' Use the attributes below to control which key is used for signing.
'
' Notes:
' (*) If no key is specified, the assembly is not signed.
' (*) KeyName refers to a key that has been installed in the Crypto Service
' Provider (CSP) on your machine. KeyFile refers to a file which contains
' a key.
' (*) If the KeyFile and the KeyName values are both specified, the
' following processing occurs:
' (1) If the KeyName can be found in the CSP, that key is used.
' (2) If the KeyName does not exist and the KeyFile does exist, the key
' in the KeyFile is installed into the CSP and used.
' (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
' When specifying the KeyFile, the location of the KeyFile should be
' relative to the project output directory which is
' %Project Directory%\obj\<configuration>. For example, if your KeyFile is
' located in the project directory, you would specify the AssemblyKeyFile
' attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
' (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
' documentation for more information on this.
'
<Assembly: AssemblyDelaySign(False)>
<Assembly: AssemblyKeyFile("")>
<Assembly: AssemblyKeyName("")>
Form1.Designer.vb
Imports System.Collections
Imports System.ComponentModel
Imports System.IO
Imports System.Reflection
Imports FlexCel.Core
Imports FlexCel.XlsAdapter
Imports FlexCel.Report
Imports FlexCel.Demo.SharedData
Namespace PivotTables
Partial Public Class mainForm
Inherits System.Windows.Forms.Form
Private WithEvents button1 As System.Windows.Forms.Button
Private saveFileDialog1 As System.Windows.Forms.SaveFileDialog
Private label1 As System.Windows.Forms.Label
Private WithEvents btnCancel As System.Windows.Forms.Button
''' <summary>
''' Required designer variable.
''' </summary>
Private components As System.ComponentModel.Container = Nothing
''' <summary>
''' Clean up any resources being used.
''' </summary>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If components IsNot Nothing Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
#Region "Windows Form Designer generated code"
''' <summary>
''' Required method for Designer support - do not modify
''' the contents of this method with the code editor.
''' </summary>
Private Sub InitializeComponent()
Me.button1 = New System.Windows.Forms.Button()
Me.saveFileDialog1 = New System.Windows.Forms.SaveFileDialog()
Me.label1 = New System.Windows.Forms.Label()
Me.btnCancel = New System.Windows.Forms.Button()
Me.SuspendLayout()
'
' button1
'
Me.button1.Anchor = (CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
Me.button1.BackColor = System.Drawing.Color.Green
Me.button1.ForeColor = System.Drawing.Color.White
Me.button1.Location = New System.Drawing.Point(152, 88)
Me.button1.Name = "button1"
Me.button1.Size = New System.Drawing.Size(112, 23)
Me.button1.TabIndex = 0
Me.button1.Text = "GO!"
Me.button1.UseVisualStyleBackColor = False
' Me.button1.Click += New System.EventHandler(Me.button1_Click)
'
' saveFileDialog1
'
Me.saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All files|*.*"
Me.saveFileDialog1.RestoreDirectory = True
'
' label1
'
Me.label1.Location = New System.Drawing.Point(24, 24)
Me.label1.Name = "label1"
Me.label1.Size = New System.Drawing.Size(288, 24)
Me.label1.TabIndex = 2
Me.label1.Text = "A pivot table with data refreshed from FlexCel."
'
' btnCancel
'
Me.btnCancel.Anchor = (CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
Me.btnCancel.BackColor = System.Drawing.Color.FromArgb((CInt((CByte(192)))), (CInt((CByte(0)))), (CInt((CByte(0)))))
Me.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.btnCancel.ForeColor = System.Drawing.Color.White
Me.btnCancel.Location = New System.Drawing.Point(272, 88)
Me.btnCancel.Name = "btnCancel"
Me.btnCancel.Size = New System.Drawing.Size(112, 23)
Me.btnCancel.TabIndex = 3
Me.btnCancel.Text = "Cancel"
Me.btnCancel.UseVisualStyleBackColor = False
' Me.btnCancel.Click += New System.EventHandler(Me.btnCancel_Click)
'
' mainForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(416, 133)
Me.Controls.Add(Me.btnCancel)
Me.Controls.Add(Me.label1)
Me.Controls.Add(Me.button1)
Me.Name = "mainForm"
Me.Text = "Pivot Tables"
Me.ResumeLayout(False)
End Sub
#End Region
End Class
End Namespace
Form1.vb
Imports System.Collections
Imports System.ComponentModel
Imports System.IO
Imports System.Reflection
Imports FlexCel.Core
Imports FlexCel.XlsAdapter
Imports FlexCel.Report
Imports FlexCel.Demo.SharedData
Namespace PivotTables
''' <summary>
''' How to keep pivot tabels in reports.
''' </summary>
Partial Public Class mainForm
Inherits System.Windows.Forms.Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
AutoRun()
End Sub
Public Sub AutoRun()
Using ordersReport As FlexCelReport = SharedData.CreateReport()
ordersReport.SetValue("Date", Date.Now)
Dim DataPath As String = Path.Combine(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), ".."), "..") & Path.DirectorySeparatorChar
If saveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim Template As String
If Path.GetExtension(saveFileDialog1.FileName) = ".xlsx" Then Template = "Pivot Tables.template.xlsx" Else Template = "Pivot Tables.template.xls"
ordersReport.Run(DataPath & Template, saveFileDialog1.FileName)
If MessageBox.Show("Do you want to open the generated file?", "Confirm", MessageBoxButtons.YesNo) = System.Windows.Forms.DialogResult.Yes Then
Process.Start(saveFileDialog1.FileName)
End If
End If
End Using
End Sub
Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Close()
End Sub
End Class
End Namespace
Program.vb
Namespace PivotTables
Friend NotInheritable Class Program
Private Sub New()
End Sub
''' <summary>
''' The main entry point for the application.
''' </summary>
<STAThread> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New mainForm())
End Sub
End Class
End Namespace