Generic reports Part 2 (VB.Net / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\vb\VS2022\netframework\20.Reports\89.Generic Reports 2 and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/vb/VS2022/netframework/Modules/20.Reports/89.Generic Reports 2
Overview
In the previous example we saw how to use <#DataTable.*> and <#DataTable.**> to create generic reports. While this works in most common cases, there are times when you might need a more complex but also more powerful approach.
Concepts
You can create a generic report by doing a report that grows both in columns and in rows.
You can use Columns(Dataset) table definition in the config sheet to have a datasource that contains the columns of the dataset. You can then use this new datasource as a source for the horizontal report (with an I_range_I), so every column in the Excel file will have one entry in the datasource.
Different from "*" reports, here you can filter this column datasource and only show some columns, or order them.
You can use <#dbvalue> tag to get the value for a column or a row. Here we use it inside a report expression in the config sheet so we don't need to write the full dbvalue tag every time.
Different from "*" reports, columns here are not overwritten, they are inserted.
A problem with this type of reports is formatting. You will want to format all dates as dates, not numbers, and you might want to format numbers as currency and so on. Here we will use a simple user-defined function to return the datatype of the value, and if it is a date then format it as date.
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("")>
EnterSQLDialog.Designer.vb
Imports System.Collections
Imports System.ComponentModel
Namespace GenericReports2
Partial Public Class EnterSQLDialog
Inherits System.Windows.Forms.Form
Private edSQL As System.Windows.Forms.TextBox
Private panel1 As System.Windows.Forms.Panel
Private label1 As System.Windows.Forms.Label
Private panel2 As System.Windows.Forms.Panel
Private btnCancel As System.Windows.Forms.Button
Private button1 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.edSQL = New System.Windows.Forms.TextBox()
Me.panel1 = New System.Windows.Forms.Panel()
Me.label1 = New System.Windows.Forms.Label()
Me.panel2 = New System.Windows.Forms.Panel()
Me.btnCancel = New System.Windows.Forms.Button()
Me.button1 = New System.Windows.Forms.Button()
Me.panel1.SuspendLayout()
Me.panel2.SuspendLayout()
Me.SuspendLayout()
'
' edSQL
'
Me.edSQL.Dock = System.Windows.Forms.DockStyle.Fill
Me.edSQL.Location = New System.Drawing.Point(0, 24)
Me.edSQL.Multiline = True
Me.edSQL.Name = "edSQL"
Me.edSQL.Size = New System.Drawing.Size(520, 125)
Me.edSQL.TabIndex = 0
Me.edSQL.Text = "Select * from orders"
'
' panel1
'
Me.panel1.BackColor = System.Drawing.Color.Gray
Me.panel1.Controls.Add(Me.label1)
Me.panel1.Dock = System.Windows.Forms.DockStyle.Top
Me.panel1.ForeColor = System.Drawing.Color.White
Me.panel1.Location = New System.Drawing.Point(0, 0)
Me.panel1.Name = "panel1"
Me.panel1.Size = New System.Drawing.Size(520, 24)
Me.panel1.TabIndex = 1
'
' label1
'
Me.label1.Font = New System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, (CByte(0)))
Me.label1.Location = New System.Drawing.Point(17, 6)
Me.label1.Name = "label1"
Me.label1.Size = New System.Drawing.Size(296, 23)
Me.label1.TabIndex = 0
Me.label1.Text = "Enter SQL to execute"
'
' panel2
'
Me.panel2.BackColor = System.Drawing.Color.Gray
Me.panel2.Controls.Add(Me.btnCancel)
Me.panel2.Controls.Add(Me.button1)
Me.panel2.Dock = System.Windows.Forms.DockStyle.Bottom
Me.panel2.ForeColor = System.Drawing.Color.White
Me.panel2.Location = New System.Drawing.Point(0, 149)
Me.panel2.Name = "panel2"
Me.panel2.Size = New System.Drawing.Size(520, 40)
Me.panel2.TabIndex = 2
'
' 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((CByte(192)), (CByte(0)), (CByte(0)))
Me.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.btnCancel.ForeColor = System.Drawing.Color.White
Me.btnCancel.Location = New System.Drawing.Point(400, 9)
Me.btnCancel.Name = "btnCancel"
Me.btnCancel.Size = New System.Drawing.Size(112, 23)
Me.btnCancel.TabIndex = 5
Me.btnCancel.Text = "Cancel"
'
' 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.DialogResult = System.Windows.Forms.DialogResult.OK
Me.button1.ForeColor = System.Drawing.Color.White
Me.button1.Location = New System.Drawing.Point(280, 9)
Me.button1.Name = "button1"
Me.button1.Size = New System.Drawing.Size(112, 23)
Me.button1.TabIndex = 4
Me.button1.Text = "Ok"
'
' EnterSQLDialog
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(520, 189)
Me.Controls.Add(Me.edSQL)
Me.Controls.Add(Me.panel2)
Me.Controls.Add(Me.panel1)
Me.Name = "EnterSQLDialog"
Me.Text = "Information"
Me.panel1.ResumeLayout(False)
Me.panel2.ResumeLayout(False)
Me.ResumeLayout(False)
End Sub
#End Region
End Class
End Namespace
EnterSQLDialog.vb
Imports System.Collections
Imports System.ComponentModel
Namespace GenericReports2
''' <summary>
''' A dialog where you can enter any SQL.
''' </summary>
Partial Public Class EnterSQLDialog
Inherits System.Windows.Forms.Form
Public Sub New()
InitializeComponent()
End Sub
Public ReadOnly Property SQL() As String
Get
Return edSQL.Text
End Get
End Property
End Class
End Namespace
Form1.Designer.vb
Imports System.Collections
Imports System.ComponentModel
Imports System.IO
Imports System.Reflection
Imports System.Data.OleDb
Imports System.Threading
Imports FlexCel.Core
Imports FlexCel.XlsAdapter
Imports FlexCel.Report
Namespace GenericReports2
Partial Public Class mainForm
Inherits System.Windows.Forms.Form
Private saveFileDialog1 As System.Windows.Forms.SaveFileDialog
Private dataSet As System.Data.DataSet
Private dataGrid As System.Windows.Forms.DataGrid
Private Connection As System.Data.OleDb.OleDbConnection
Private dbDataAdapter As System.Data.OleDb.OleDbDataAdapter
Private Report As FlexCel.Report.FlexCelReport
Private components As System.ComponentModel.IContainer = 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()
Dim resources As New System.ComponentModel.ComponentResourceManager(GetType(mainForm))
Me.saveFileDialog1 = New System.Windows.Forms.SaveFileDialog()
Me.Report = New FlexCel.Report.FlexCelReport()
Me.Connection = New System.Data.OleDb.OleDbConnection()
Me.dataSet = New System.Data.DataSet()
Me.dataGrid = New System.Windows.Forms.DataGrid()
Me.dbDataAdapter = New System.Data.OleDb.OleDbDataAdapter()
Me.mainToolbar = New System.Windows.Forms.ToolStrip()
Me.btnOpenConnection = New System.Windows.Forms.ToolStripButton()
Me.btnQuery = New System.Windows.Forms.ToolStripButton()
Me.toolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator()
Me.btnExportExcel = New System.Windows.Forms.ToolStripButton()
Me.btnExit = New System.Windows.Forms.ToolStripButton()
CType(Me.dataSet, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.dataGrid, System.ComponentModel.ISupportInitialize).BeginInit()
Me.mainToolbar.SuspendLayout()
Me.SuspendLayout()
'
' saveFileDialog1
'
Me.saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All " & "files|*.*"
Me.saveFileDialog1.RestoreDirectory = True
'
' Report
'
Me.Report.AllowOverwritingFiles = True
Me.Report.DeleteEmptyBands = FlexCel.Report.TDeleteEmptyBands.ClearDataAndFormats
Me.Report.DeleteEmptyRanges = False
'
' dataSet
'
Me.dataSet.DataSetName = "NewDataSet"
Me.dataSet.Locale = New System.Globalization.CultureInfo("es-ES")
'
' dataGrid
'
Me.dataGrid.DataMember = ""
Me.dataGrid.Dock = System.Windows.Forms.DockStyle.Fill
Me.dataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText
Me.dataGrid.Location = New System.Drawing.Point(0, 38)
Me.dataGrid.Name = "dataGrid"
Me.dataGrid.Size = New System.Drawing.Size(528, 239)
Me.dataGrid.TabIndex = 4
'
' mainToolbar
'
Me.mainToolbar.Items.AddRange(New System.Windows.Forms.ToolStripItem() { Me.btnOpenConnection, Me.btnQuery, Me.toolStripSeparator1, Me.btnExportExcel, Me.btnExit})
Me.mainToolbar.Location = New System.Drawing.Point(0, 0)
Me.mainToolbar.Name = "mainToolbar"
Me.mainToolbar.Size = New System.Drawing.Size(528, 38)
Me.mainToolbar.TabIndex = 11
Me.mainToolbar.Text = "mainToolbar"
'
' btnOpenConnection
'
Me.btnOpenConnection.Image = (CType(resources.GetObject("btnOpenConnection.Image"), System.Drawing.Image))
Me.btnOpenConnection.ImageTransparentColor = System.Drawing.Color.Magenta
Me.btnOpenConnection.Name = "btnOpenConnection"
Me.btnOpenConnection.Size = New System.Drawing.Size(103, 35)
Me.btnOpenConnection.Text = "Open connection"
Me.btnOpenConnection.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
' Me.btnOpenConnection.Click += New System.EventHandler(Me.btnOpenconnection_Click)
'
' btnQuery
'
Me.btnQuery.Image = (CType(resources.GetObject("btnQuery.Image"), System.Drawing.Image))
Me.btnQuery.ImageTransparentColor = System.Drawing.Color.Magenta
Me.btnQuery.Name = "btnQuery"
Me.btnQuery.Size = New System.Drawing.Size(70, 35)
Me.btnQuery.Text = "Query Data"
Me.btnQuery.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
' Me.btnQuery.Click += New System.EventHandler(Me.btnQuery_Click)
'
' toolStripSeparator1
'
Me.toolStripSeparator1.Name = "toolStripSeparator1"
Me.toolStripSeparator1.Size = New System.Drawing.Size(6, 38)
'
' btnExportExcel
'
Me.btnExportExcel.Image = (CType(resources.GetObject("btnExportExcel.Image"), System.Drawing.Image))
Me.btnExportExcel.ImageTransparentColor = System.Drawing.Color.Magenta
Me.btnExportExcel.Name = "btnExportExcel"
Me.btnExportExcel.Size = New System.Drawing.Size(87, 35)
Me.btnExportExcel.Text = "Export to Excel"
Me.btnExportExcel.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
' Me.btnExportExcel.Click += New System.EventHandler(Me.btnExportExcel_Click)
'
' btnExit
'
Me.btnExit.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right
Me.btnExit.Image = (CType(resources.GetObject("btnExit.Image"), System.Drawing.Image))
Me.btnExit.ImageTransparentColor = System.Drawing.Color.Magenta
Me.btnExit.Name = "btnExit"
Me.btnExit.Size = New System.Drawing.Size(59, 35)
Me.btnExit.Text = " E&xit "
Me.btnExit.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText
' Me.btnExit.Click += New System.EventHandler(Me.button2_Click)
'
' mainForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(528, 277)
Me.Controls.Add(Me.dataGrid)
Me.Controls.Add(Me.mainToolbar)
Me.Name = "mainForm"
Me.Text = "Generic Reports 2"
CType(Me.dataSet, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.dataGrid, System.ComponentModel.ISupportInitialize).EndInit()
Me.mainToolbar.ResumeLayout(False)
Me.mainToolbar.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
#End Region
Private mainToolbar As ToolStrip
Private WithEvents btnOpenConnection As ToolStripButton
Private WithEvents btnQuery As ToolStripButton
Private toolStripSeparator1 As ToolStripSeparator
Private WithEvents btnExportExcel As ToolStripButton
Private WithEvents btnExit As ToolStripButton
End Class
End Namespace
Form1.vb
Imports System.Collections
Imports System.ComponentModel
Imports System.IO
Imports System.Reflection
Imports System.Data.OleDb
Imports System.Threading
Imports FlexCel.Core
Imports FlexCel.XlsAdapter
Imports FlexCel.Report
Namespace GenericReports2
''' <summary>
''' A generic report.
''' </summary>
Partial Public Class mainForm
Inherits System.Windows.Forms.Form
Private SqlDialog As EnterSQLDialog
Public Sub New()
InitializeComponent()
ResizeToolbar(mainToolbar)
End Sub
Private Sub ResizeToolbar(ByVal toolbar As ToolStrip)
Using gr As Graphics = CreateGraphics()
Dim xFactor As Double = gr.DpiX / 96.0
Dim yFactor As Double = gr.DpiY / 96.0
toolbar.ImageScalingSize = New Size(CInt(Fix(24 * xFactor)), CInt(Fix(24 * yFactor)))
toolbar.Width = 0 'force a recalc of the buttons.
End Using
End Sub
Private Sub button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExit.Click
Close()
End Sub
Private Sub btnOpenconnection_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOpenConnection.Click
Dim DataPath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & Path.DirectorySeparatorChar
Dim ConfigFile As String = DataPath & "GenericReports2.udl"
If Not File.Exists(ConfigFile) Then
Using f As FileStream = File.Create(ConfigFile)
'Nothing, create an empty udl.
End Using
End If
Process.Start(ConfigFile)
End Sub
Private Sub btnQuery_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnQuery.Click
Dim DataPath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & Path.DirectorySeparatorChar
Dim ConfigFile As String = DataPath & "GenericReports2.udl"
Connection.Close()
dataSet = New DataSet()
Connection.ConnectionString = "File Name = " & ConfigFile
Connection.Open()
If SqlDialog Is Nothing Then
SqlDialog = New EnterSQLDialog()
End If
If SqlDialog.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
Return
End If
dbDataAdapter.SelectCommand = New OleDbCommand(SqlDialog.SQL, Connection)
dbDataAdapter.Fill(dataSet, "Table")
dataGrid.CaptionText = dbDataAdapter.SelectCommand.CommandText
dataGrid.SetDataBinding(dataSet, "Table")
End Sub
Private Sub Export(ByVal SQL As String, ByRef DataPath As String)
Report.ClearTables()
Report.AddTable(dataSet)
Report.SetValue("Date", Date.Now)
Report.SetValue("ReportCaption", SQL)
Report.SetUserFunction("datatype", New DataTypeImp())
DataPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & Path.DirectorySeparatorChar 'First try to find the template on exe folder.
If Not File.Exists(DataPath & "Generic Reports 2.template.xls") Then 'When on design mode, search for the template 2 folders up.
DataPath = Path.Combine(DataPath, Path.Combine("..", "..")) & Path.DirectorySeparatorChar
End If
End Sub
Private Sub btnExportExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportExcel.Click
Dim DataPath As String = Nothing
If dbDataAdapter Is Nothing OrElse dbDataAdapter.SelectCommand Is Nothing OrElse dbDataAdapter.SelectCommand.CommandText Is Nothing Then
MessageBox.Show("You need to select a query first")
Return
End If
Export(dbDataAdapter.SelectCommand.CommandText, DataPath)
If saveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Report.Run(DataPath & "Generic Reports 2.template.xls", 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 Sub
End Class
''' <summary>
''' A small used-defined function to know the type of the value inserted.
''' </summary>
Public Class DataTypeImp
Inherits TFlexCelUserFunction
Public Overrides Function Evaluate(ByVal parameters() As Object) As Object
If parameters Is Nothing OrElse parameters.Length <> 1 Then
Throw New Exception("DataType must be called with 1 parameter.")
End If
If TypeOf parameters(0) Is Double Then
Return "double"
End If
If TypeOf parameters(0) Is Date Then
Return "datetime"
End If
Return ""
End Function
End Class
End Namespace
Program.vb
Imports System.Threading
Namespace GenericReports2
Friend NotInheritable Class Program
Private Sub New()
End Sub
''' <summary>
''' The main entry point for the application.
''' </summary>
<STAThread> _
Shared Sub Main()
Dim handler As New ThreadExceptionHandler()
AddHandler Application.ThreadException, AddressOf handler.Application_ThreadException
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New mainForm())
End Sub
End Class
Friend Class ThreadExceptionHandler
Public Sub Application_ThreadException(ByVal sender As Object, ByVal e As ThreadExceptionEventArgs)
Try
Dim result As DialogResult = ShowThreadExceptionDialog(e.Exception)
If result = DialogResult.Abort Then
Application.Exit()
End If
Catch
' Fatal error, terminate program
Try
MessageBox.Show("Fatal Error", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Finally
Application.Exit()
End Try
End Try
End Sub
'''
''' Creates and displays the error message.
'''
Private Function ShowThreadExceptionDialog(ByVal ex As Exception) As DialogResult
Dim errorMessage As String = "Unhandled Exception:" & vbLf & vbLf & ex.Message & vbLf & vbLf & ex.GetType().ToString() & vbLf & vbLf & "Stack Trace:" & vbLf & ex.StackTrace
Return MessageBox.Show(errorMessage, "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
End Function
End Class
End Namespace