User defined formats (VB.Net / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\vb\VS2022\netframework\20.Reports\95b.User Defined Formats and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/vb/VS2022/netframework/Modules/20.Reports/95b.User Defined Formats
Overview
User defined formats are a way to format cells in a report with code. Normally you will want to use them if the data to format the cells is in the database and it is not known at compile time, so you can't use conditional formatting or formats defined in the config sheet.
Concepts
How to define and use a user defined format.
You can pass parameters to the user defined format by writing them after the format name. In this example we show passing one parameter (in user format "ZipCode") and two parameters (in user format "ShipFormat").
If you don't want to modify the format then return a null TFlxFormat and a null TFlxApplyFormat. We do this in the ZipCode user format, when the zip code is not numeric. If you wanted to return a format but not apply, you could set only the TFlxApplyFormat to null and the full TFlxFormat would be applied.
As you can see, the colors in this demo don't make much sense. There is a reason for that: trying to find an example of stuff that can only be made with user defined formats is not easy. If you wanted for example to mark red the cells where a value is > 100, then you would just use an Excel conditional format instead. The recommended order of preference would be:
If you can do it with Excel conditional formats, then use that.
If you can't use conditional formats then use formats defined in the config sheet
For more complex formats where you can't use any of the above (like for example if the color of the cell is stored in the database, or the rules are too complex to code them in a conditional format or the config sheet), then use user defined formats.
You can use user defined formats to format rows, columns or cells. As format cell has more priority than format row, in this example there are cells which override the row format.
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 UserDefinedFormats
Partial Public Class mainForm
Inherits System.Windows.Forms.Form
''' <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 report using an user defined format."
'
' 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 = "User defined formats"
Me.ResumeLayout(False)
End Sub
#End Region
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
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 UserDefinedFormats
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)
ordersReport.SetUserFormat("ZipCode", New ZipCodeImp())
ordersReport.SetUserFormat("ShipFormat", New ShipFormatImp())
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
ordersReport.Run(DataPath & "User Defined Formats.template.xlsx", 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
#Region "ZipCode Implementation"
Friend Class ZipCodeImp
Inherits TFlexCelUserFormat
Public Sub New()
End Sub
Public Overrides Function Evaluate(ByVal workbook As ExcelFile, ByVal rangeToFormat As TXlsCellRange, ByVal parameters() As Object) As TFlxPartialFormat
If parameters Is Nothing OrElse parameters.Length <> 1 Then
Throw New ArgumentException("Bad parameter count in call to ZipCode() user-defined format")
End If
Dim color As Integer
'If the zip code is not valid, don't modify the format.
If parameters(0) Is Nothing OrElse (Not Integer.TryParse(Convert.ToString(parameters(0)), color)) Then
Return New TFlxPartialFormat(Nothing, Nothing, False)
End If
'This code is not supposed to make sense. We will convert the zip code to a color based in the numeric value.
Dim fmt As TFlxFormat = workbook.GetDefaultFormat
fmt.FillPattern.Pattern = TFlxPatternStyle.Solid
fmt.FillPattern.FgColor = TExcelColor.FromArgb(color)
fmt.FillPattern.BgColor = TExcelColor.Automatic
fmt.Font.Color = TExcelColor.FromArgb((Not color))
Dim apply As New TFlxApplyFormat()
apply.FillPattern.SetAllMembers(True)
apply.Font.Color = True
Return New TFlxPartialFormat(fmt, apply, False)
End Function
End Class
#End Region
#Region "ShipFormat Implementation"
Friend Class ShipFormatImp
Inherits TFlexCelUserFormat
Public Sub New()
End Sub
Public Overrides Function Evaluate(ByVal workbook As ExcelFile, ByVal rangeToFormat As TXlsCellRange, ByVal parameters() As Object) As TFlxPartialFormat
'Again, this example is not supposed to make sense, only to show how you can code a complex rule.
'This method will format the rows with a color that depends in the length of the first parameter,
'and if the second parameter starts with "B" it will make the text red.
If parameters Is Nothing OrElse parameters.Length <> 2 Then
Throw New ArgumentException("Bad parameter count in call to ShipFormat() user-defined format")
End If
Dim len As Integer = Convert.ToString(parameters(0)).Length
Dim country As String = Convert.ToString(parameters(1))
Dim color As Int32 = &HFFFFFF - len * 100
Dim fmt As TFlxFormat = workbook.GetDefaultFormat
fmt.FillPattern.Pattern = TFlxPatternStyle.Solid
fmt.FillPattern.FgColor = TExcelColor.FromArgb(color)
fmt.FillPattern.BgColor = TExcelColor.Automatic
Dim apply As New TFlxApplyFormat()
apply.FillPattern.SetAllMembers(True)
If country.StartsWith("B") Then
fmt.Font.Color = Colors.OrangeRed
apply.Font.Color = True
End If
Return New TFlxPartialFormat(fmt, apply, False)
End Function
End Class
#End Region
End Namespace
Program.vb
Namespace UserDefinedFormats
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