Table of Contents

Getting started with Reports (VB.Net / netframework)

Note

This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\vb\VS2022\netframework\20.Reports\10.Getting Started Reports and also at https:​//​github.​com/​tmssoftware/​TMS-​FlexCel.​NET-​demos/​tree/​master/​vb/​VS2022/​netframework/​Modules/​20.​Reports/​10.​Getting Started Reports

Overview

A really simple demo on how to create an Excel report. No database is used, only report variables.

Concepts

  • A template is an Excel file with tags that will be replaced by report variables or fields from a dataset. Tags are always on the form <#tag> If a tag has parameters, it always has the form <#tag(param1; param2...)>. You can read the FlexCel Reports Tag Reference. for more information.

  • To set the value for report variable, use FlexCelReport.SetValue. You can set any kind of object from here, not just text. If you set it to a TFormula object, you will enter a formula.

  • <#Tags> will be replaced inside Cells, Comments, Sheet names, Images, Hyperlinks, AutoShapes, Headers and Footers. All of this is shown here. To see the headers and footers, you must do a print preview.

  • There are 2 special datatypes you must be aware:

    1. Dates: Dates in Excel are just numbers, with a special cell format. To enter a date in Excel, make sure the cell has a date format.

    2. Multiline Text:To be able to show carriage return on a cell, it must have "Wrap text" enabled on its cell format.

  • Hyperlinks are a special case for 2 reasons:

    1. You can't enter <# into an hyperlink, as # is a reserved keyword. So, tags in hyperlinks are on the form "*.TAG.*" (On older FlexCelVersions we would use "<.tag>". This will still work, but you can't enter this text into Excel 2003 or newer)

    2. If you do not begin the hyperlink text with "http://" or "https://" while creating the link in Excel, it will be created as local file. As this is not what you would normally want, all "local file" hyperlinks will be changed to URL hyperlinks if the replaced text starts with "http:" or "https:". So do not create links like "www.tmssoftware.com", make your hyperlinks "https://www.tmssoftware.com"

  • To create an hyperlink to a cell in the same file using tags, start the definition of the hyperlink with a "#", like "*.sheetvar.*!*.#cellvar.*"

  • There are special tags, like the <#If( condition, iftrue, iffalse)> that might contain other tags inside. You can use any composition of tags on any of the places where they will be replaced.

  • Empty comments will be removed. This is a feature so you can selectively comment cells based on the comment text. If comment text is blank, no comment will be made.

  • To replace images, name them as <#tag>. To see or change the name of an image, use the combo box at the upper left corner on Excel.

  • You can use tags as usual on sheet names. But, as the maximum sheet name length is 32, it is kind of limited. You can use Equal tag (<#=(cell)>) to solve this limitation.

  • You can define reusable variables on the config sheet. For example, here we define an expression containing the name and "anonymous" if the name is null, and we use it on the sheet name and the print header. Then we can use this expression on many places. <#=(cell)> is conceptually the same as report expressions, but report expressions are normally cleaner on what they mean.

  • Rich text will be preserved on cells. If for example you write "<#name> and <#date>", the result will be "your name and thedate"

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
Namespace GettingStartedReports
	Partial Public Class mainForm
		Inherits System.Windows.Forms.Form

		Private WithEvents btnGo As System.Windows.Forms.Button
		Private saveFileDialog1 As System.Windows.Forms.SaveFileDialog

		Private edName As System.Windows.Forms.TextBox
		Private label1 As System.Windows.Forms.Label
		Private WithEvents btnCancel As System.Windows.Forms.Button
		Private label2 As System.Windows.Forms.Label
		Private edUrl As System.Windows.Forms.TextBox
		Private cbAutoOpen As System.Windows.Forms.CheckBox
		Private reportStart As FlexCel.Report.FlexCelReport

		''' <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.btnGo = New System.Windows.Forms.Button()
			Me.saveFileDialog1 = New System.Windows.Forms.SaveFileDialog()
			Me.reportStart = New FlexCel.Report.FlexCelReport()
			Me.edName = New System.Windows.Forms.TextBox()
			Me.label1 = New System.Windows.Forms.Label()
			Me.btnCancel = New System.Windows.Forms.Button()
			Me.label2 = New System.Windows.Forms.Label()
			Me.edUrl = New System.Windows.Forms.TextBox()
			Me.cbAutoOpen = New System.Windows.Forms.CheckBox()
			Me.SuspendLayout()
			' 
			' btnGo
			' 
			Me.btnGo.Anchor = (CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
			Me.btnGo.BackColor = System.Drawing.Color.Green
			Me.btnGo.ForeColor = System.Drawing.Color.White
			Me.btnGo.Location = New System.Drawing.Point(152, 152)
			Me.btnGo.Name = "btnGo"
			Me.btnGo.Size = New System.Drawing.Size(112, 24)
			Me.btnGo.TabIndex = 0
			Me.btnGo.Text = "GO!"
			Me.btnGo.UseVisualStyleBackColor = False
'			Me.btnGo.Click += New System.EventHandler(Me.btnGo_Click)
			' 
			' saveFileDialog1
			' 
			Me.saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All " & "files|*.*"
			Me.saveFileDialog1.RestoreDirectory = True
			' 
			' reportStart
			' 
			Me.reportStart.AllowOverwritingFiles = True
			Me.reportStart.DeleteEmptyRanges = False
			' 
			' edName
			' 
			Me.edName.Anchor = (CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
			Me.edName.Location = New System.Drawing.Point(24, 40)
			Me.edName.Name = "edName"
			Me.edName.Size = New System.Drawing.Size(360, 20)
			Me.edName.TabIndex = 1
			' 
			' label1
			' 
			Me.label1.Location = New System.Drawing.Point(24, 24)
			Me.label1.Name = "label1"
			Me.label1.Size = New System.Drawing.Size(160, 16)
			Me.label1.TabIndex = 2
			Me.label1.Text = "Tell me your name:"
			' 
			' btnCancel
			' 
			Me.btnCancel.Anchor = (CType((System.Windows.Forms.AnchorStyles.Bottom 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, 152)
			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)
			' 
			' label2
			' 
			Me.label2.Location = New System.Drawing.Point(28, 60)
			Me.label2.Name = "label2"
			Me.label2.Size = New System.Drawing.Size(228, 16)
			Me.label2.TabIndex = 5
			Me.label2.Text = "Your Home page (without http://)"
			' 
			' edUrl
			' 
			Me.edUrl.Anchor = (CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
			Me.edUrl.Location = New System.Drawing.Point(28, 76)
			Me.edUrl.Name = "edUrl"
			Me.edUrl.Size = New System.Drawing.Size(360, 20)
			Me.edUrl.TabIndex = 4
			Me.edUrl.Text = "www.tmssoftware.com"
			' 
			' cbAutoOpen
			' 
			Me.cbAutoOpen.Location = New System.Drawing.Point(24, 104)
			Me.cbAutoOpen.Name = "cbAutoOpen"
			Me.cbAutoOpen.Size = New System.Drawing.Size(264, 24)
			Me.cbAutoOpen.TabIndex = 6
			Me.cbAutoOpen.Text = "Auto open the generated file without saving it"
			' 
			' mainForm
			' 
			Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
			Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
			Me.ClientSize = New System.Drawing.Size(416, 190)
			Me.Controls.Add(Me.cbAutoOpen)
			Me.Controls.Add(Me.label2)
			Me.Controls.Add(Me.edUrl)
			Me.Controls.Add(Me.btnCancel)
			Me.Controls.Add(Me.label1)
			Me.Controls.Add(Me.edName)
			Me.Controls.Add(Me.btnGo)
			Me.Name = "mainForm"
			Me.Text = "Getting Started"
			Me.ResumeLayout(False)
			Me.PerformLayout()

		End Sub
		#End Region
	End Class
End Namespace


Form1.vb

Imports System.Collections
Imports System.ComponentModel
Imports System.IO
Imports System.Reflection
Imports System.Threading
Imports FlexCel.Core
Imports FlexCel.XlsAdapter
Imports FlexCel.Report


Namespace GettingStartedReports
	''' <summary>
	''' Simple report
	''' </summary>
	Partial Public Class mainForm
		Inherits System.Windows.Forms.Form

		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub btnGo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGo.Click
			'Note that we are using a FlexCelReport component in a form here. We could also create the FlexCelReport component dynamically.

			If cbAutoOpen.Checked Then
				AutoOpenRun()
			Else
				NormalRun()
			End If
		End Sub

		Private Sub Setup(ByVal UserName As String, ByVal UserUrl As String, ByVal DataPath As String)
			'Set report variables, including an image.

			reportStart.SetValue("Date", Date.Now)
			reportStart.SetValue("Name", UserName)
			reportStart.SetValue("TwoLines", "First line" & Environment.NewLine & "Second Line")
			reportStart.SetValue("Empty", Nothing)
			reportStart.SetValue("LinkPage", UserUrl)
			reportStart.SetValue("Img", File.ReadAllBytes(Path.Combine(DataPath, "img.png")))
		End Sub


		Private Sub NormalRun()
			Dim DataPath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
			DataPath = Path.Combine(DataPath, "..")
			DataPath = Path.Combine(DataPath, "..")
			Setup(edName.Text, edUrl.Text, DataPath)

			If saveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
				'FlexCel isn't a conversion tool. While it does a good job converting a lot of stuff
				'between xls and xlsx, for best results we will use an xlsx template if the user choose xlsx and xls if the user choose xls.
				reportStart.Run(Path.Combine(DataPath, "Getting Started Reports.template" & Path.GetExtension(saveFileDialog1.FileName)), 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



        Private Sub AutoOpenRun()
            Dim DataPath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
            DataPath = Path.Combine(DataPath, "..")
            DataPath = Path.Combine(DataPath, "..")
            Setup(edName.Text, edUrl.Text, DataPath)

            Dim Xls As New XlsFile()
            Xls.Open(Path.Combine(DataPath, "Getting Started Reports.template.xlsx"))
            reportStart.Run(Xls)

            Dim FilePath As String = Path.GetTempPath() 'GetTempFileName does not allow us to specify the "xltx" extension.
            Dim FileName As String = Path.Combine(FilePath, Guid.NewGuid().ToString() & ".xltx") 'xltx is the extension for excel templates.
            Try
                Using OutStream As New FileStream(FileName, FileMode.Create, FileAccess.ReadWrite)
                    Xls.IsXltTemplate = True 'Make it an xltx template.
                    Xls.Save(OutStream)
                End Using
                Process.Start(FileName)
            Finally
                'For .Net 4 and newer you can use Task.Run here. See https://doc.tmssoftware.com/flexcel/net/tips/automatically-open-generated-excel-files.html
                Dim t As New Thread(AddressOf RemoveTempAfterUse)
                t.Start(FileName)
            End Try
		End Sub

        Private Sub RemoveTempAfterUse(ByVal FileName As Object)
            'As it is an xltx file, we can delete it even when it is open on Excel. - wait for 30 secs to give Excel time to start.
            Thread.Sleep(30000)
            File.Delete(CType(FileName, String))
        End Sub

        ''' <summary>
        ''' This is the method that will be called by the ASP.NET front end. It returns an array of bytes 
        ''' with the report data, so the ASP.NET application can stream it to the client.
        ''' </summary>
        ''' <param name="UserName"></param>
        ''' <param name="UserUrl"></param>
        ''' <returns>The generated file as a byte array.</returns>
        Public Function WebRun(ByVal UserName As String, ByVal UserUrl As String) As Byte()
            Dim DataPath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
            DataPath = Path.Combine(DataPath, "..")
            DataPath = Path.Combine(DataPath, "..")
            Setup(UserName, UserUrl, DataPath)

            Using OutStream As New MemoryStream()
                Using InStream As New FileStream(Path.Combine(DataPath, "Getting Started Reports.template.xls"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
                    reportStart.Run(InStream, OutStream)
                    Return OutStream.ToArray()
                End Using
            End Using
        End Function


        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 GettingStartedReports
	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