Getting started with Reports (C# / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\csharp\VS2022\netframework\20.Reports\10.Getting Started Reports and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/csharp/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:
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.
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:
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)
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.cs
using System.Reflection;
using 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 - 2024 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("7.21.0.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.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using FlexCel.Core;
using FlexCel.XlsAdapter;
using FlexCel.Report;
namespace GettingStartedReports
{
/// <summary>
/// Simple report
/// </summary>
public partial class mainForm: System.Windows.Forms.Form
{
public mainForm()
{
InitializeComponent();
}
private void btnGo_Click(object sender, System.EventArgs e)
{
//Note that we are using a FlexCelReport component in a form here. We could also create the FlexCelReport component dynamically.
if (cbAutoOpen.Checked)
AutoOpenRun();
else
NormalRun();
}
private void Setup(string UserName, string UserUrl, string DataPath)
{
//Set report variables, including an image.
reportStart.SetValue("Date", DateTime.Now);
reportStart.SetValue("Name", UserName);
reportStart.SetValue("TwoLines", "First line" + Environment.NewLine + "Second Line");
reportStart.SetValue("Empty", null);
reportStart.SetValue("LinkPage", UserUrl);
reportStart.SetValue("Img", File.ReadAllBytes(Path.Combine(DataPath, "img.png")));
}
private void NormalRun()
{
string DataPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
DataPath = Path.Combine(DataPath, "..");
DataPath = Path.Combine(DataPath, "..");
Setup(edName.Text, edUrl.Text, DataPath);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//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) == DialogResult.Yes)
{
using (Process p = new Process())
{
p.StartInfo.FileName = saveFileDialog1.FileName;
p.StartInfo.UseShellExecute = true;
p.Start();
}
}
}
}
private void AutoOpenRun()
{
string DataPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
DataPath = Path.Combine(DataPath, "..");
DataPath = Path.Combine(DataPath, "..");
Setup(edName.Text, edUrl.Text, DataPath);
XlsFile Xls = new XlsFile();
Xls.Open(Path.Combine(DataPath, "Getting Started Reports.template.xlsx"));
reportStart.Run(Xls);
string FilePath = Path.GetTempPath(); //GetTempFileName does not allow us to specify the "xltx" extension.
string FileName = Path.Combine(FilePath, Guid.NewGuid().ToString() + ".xltx"); //xltx is the extension for excel templates.
try
{
using (FileStream OutStream = new FileStream(FileName, FileMode.Create, FileAccess.ReadWrite))
{
Xls.IsXltTemplate = true; //Make it an xltx template.
Xls.Save(OutStream);
}
using (Process p = new Process())
{
p.StartInfo.FileName = FileName;
p.StartInfo.UseShellExecute = true;
p.Start();
}
}
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
new Thread(delegate()
{
Thread.Sleep(30000); //wait for 30 secs to give Excel time to start.
File.Delete(FileName); //As it is an xltx file, we can delete it even when it is open on Excel.
});
}
}
/// <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 byte[] WebRun(string UserName, string UserUrl)
{
string DataPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
DataPath = Path.Combine(DataPath, "..");
DataPath = Path.Combine(DataPath, "..");
Setup(UserName, UserUrl, DataPath);
using (MemoryStream OutStream = new MemoryStream())
{
using (FileStream InStream = new FileStream(Path.Combine(DataPath, "Getting Started Reports.template.xls"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
reportStart.Run(InStream, OutStream);
return OutStream.ToArray();
}
}
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
Close();
}
}
}
Form1.Designer.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using FlexCel.Core;
using FlexCel.XlsAdapter;
using FlexCel.Report;
namespace GettingStartedReports
{
public partial class mainForm: System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnGo;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.TextBox edName;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox edUrl;
private System.Windows.Forms.CheckBox cbAutoOpen;
private FlexCel.Report.FlexCelReport reportStart;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#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 void InitializeComponent()
{
this.btnGo = new System.Windows.Forms.Button();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.reportStart = new FlexCel.Report.FlexCelReport();
this.edName = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.btnCancel = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.edUrl = new System.Windows.Forms.TextBox();
this.cbAutoOpen = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// btnGo
//
this.btnGo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnGo.BackColor = System.Drawing.Color.Green;
this.btnGo.ForeColor = System.Drawing.Color.White;
this.btnGo.Location = new System.Drawing.Point(152, 152);
this.btnGo.Name = "btnGo";
this.btnGo.Size = new System.Drawing.Size(112, 24);
this.btnGo.TabIndex = 0;
this.btnGo.Text = "GO!";
this.btnGo.UseVisualStyleBackColor = false;
this.btnGo.Click += new System.EventHandler(this.btnGo_Click);
//
// saveFileDialog1
//
this.saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All " +
"files|*.*";
this.saveFileDialog1.RestoreDirectory = true;
//
// reportStart
//
this.reportStart.AllowOverwritingFiles = true;
this.reportStart.DeleteEmptyRanges = false;
//
// edName
//
this.edName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.edName.Location = new System.Drawing.Point(24, 40);
this.edName.Name = "edName";
this.edName.Size = new System.Drawing.Size(360, 20);
this.edName.TabIndex = 1;
//
// label1
//
this.label1.Location = new System.Drawing.Point(24, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(160, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Tell me your name:";
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.ForeColor = System.Drawing.Color.White;
this.btnCancel.Location = new System.Drawing.Point(272, 152);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(112, 23);
this.btnCancel.TabIndex = 3;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = false;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// label2
//
this.label2.Location = new System.Drawing.Point(28, 60);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(228, 16);
this.label2.TabIndex = 5;
this.label2.Text = "Your Home page (without http://)";
//
// edUrl
//
this.edUrl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.edUrl.Location = new System.Drawing.Point(28, 76);
this.edUrl.Name = "edUrl";
this.edUrl.Size = new System.Drawing.Size(360, 20);
this.edUrl.TabIndex = 4;
this.edUrl.Text = "www.tmssoftware.com";
//
// cbAutoOpen
//
this.cbAutoOpen.Location = new System.Drawing.Point(24, 104);
this.cbAutoOpen.Name = "cbAutoOpen";
this.cbAutoOpen.Size = new System.Drawing.Size(264, 24);
this.cbAutoOpen.TabIndex = 6;
this.cbAutoOpen.Text = "Auto open the generated file without saving it";
//
// mainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(416, 190);
this.Controls.Add(this.cbAutoOpen);
this.Controls.Add(this.label2);
this.Controls.Add(this.edUrl);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.label1);
this.Controls.Add(this.edName);
this.Controls.Add(this.btnGo);
this.Name = "mainForm";
this.Text = "Getting Started";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
Program.cs
using System;
using System.Windows.Forms;
namespace GettingStartedReports
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainForm());
}
}
}