Generic reports (C# / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\csharp\VS2022\netframework\20.Reports\88.Generic Reports and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/csharp/VS2022/netframework/Modules/20.Reports/88.Generic Reports
Overview
When you are reporting from an unknown database (for example if you are writing a DbExport app) you can't use a fixed template, because you don't know what the columns will be. While FlexCelReport is designed to handle fixed-form templates, there is some support also for generic reports. This example together with the Meta Templates and Generic Reports 2 examples show what can be done. For more advanced generic reports, you should probably use the API directly.
Concepts
You can use <#DataTable.*> to write a full row of data from a datatable. Cells at the right of the cell containing the <#DataTable.*> tag will be overwritten.
You can use <#DataTable.**> to write a full row with the column captions on a datatable. Cells at the right of the cell containing the <#DataTable.**> tag will be overwritten.
<DataTable.**> can be placed anywhere, it doesn't need to be inside a named range. <DataTable.*> should be inside a named range populating DataTable.
Dates: As dates on Excel are just numbers formatted as date, <#DataTable.*> will format the cell when the column has a DateTime value. If the time part of the datetime is 0, time will not be entered.
You can use expressions in cells with <#DataTable.*> and <#DataTable.**> tags. You can also get the current value of the tag in the cell by writing <#DataTable.*> or <#DataTable.**> again in the same cell. For example, the tags:
<#Table.**><#Column Width(autofit;110)>
Will autofit all the columns in the range expanded by the <#Table.**> tag. While the tags:
<#Table.*><#if(<#evaluate(mod(column(),2)=0)>;<#format cell(light)>;)> <#if(<#table.*>="BONAP";<#format cell(blue)>;)> <#if(<#table.**>="OrderDate";<#format cell(longdate)>;)>
will perform 3 things: On the first, it will paint alternating columns with the "light" format. On the second, it will it will highlight cells that contain the string "BONAP" in blue. On the third, it will format the cells in the "OrderDate" column to have a longer date format.
Autofilters will be automatically expanded with the <#DataTable.**> tag. You only need to set them in the cell with the tag.
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("")]
EnterSQLDialog.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace GenericReports
{
/// <summary>
/// A dialog where you can enter any SQL.
/// </summary>
public partial class EnterSQLDialog: System.Windows.Forms.Form
{
public EnterSQLDialog()
{
InitializeComponent();
}
public string SQL
{
get
{
return edSQL.Text;
}
}
}
}
EnterSQLDialog.Designer.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace GenericReports
{
public partial class EnterSQLDialog: System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox edSQL;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button button1;
/// <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.edSQL = new System.Windows.Forms.TextBox();
this.panel1 = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.btnCancel = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// edSQL
//
this.edSQL.Dock = System.Windows.Forms.DockStyle.Fill;
this.edSQL.Location = new System.Drawing.Point(0, 24);
this.edSQL.Multiline = true;
this.edSQL.Name = "edSQL";
this.edSQL.Size = new System.Drawing.Size(520, 125);
this.edSQL.TabIndex = 0;
this.edSQL.Text = "Select * from orders";
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.Gray;
this.panel1.Controls.Add(this.label1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.ForeColor = System.Drawing.Color.White;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(520, 24);
this.panel1.TabIndex = 1;
//
// label1
//
this.label1.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(17, 6);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(296, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Enter SQL to execute";
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.Gray;
this.panel2.Controls.Add(this.btnCancel);
this.panel2.Controls.Add(this.button1);
this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel2.ForeColor = System.Drawing.Color.White;
this.panel2.Location = new System.Drawing.Point(0, 149);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(520, 40);
this.panel2.TabIndex = 2;
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(0)), ((System.Byte)(0)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.ForeColor = System.Drawing.Color.White;
this.btnCancel.Location = new System.Drawing.Point(400, 9);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(112, 23);
this.btnCancel.TabIndex = 5;
this.btnCancel.Text = "Cancel";
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.BackColor = System.Drawing.Color.Green;
this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
this.button1.ForeColor = System.Drawing.Color.White;
this.button1.Location = new System.Drawing.Point(280, 9);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(112, 23);
this.button1.TabIndex = 4;
this.button1.Text = "Ok";
//
// EnterSQLDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(520, 189);
this.Controls.Add(this.edSQL);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Name = "EnterSQLDialog";
this.Text = "Information";
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
}
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.Data.OleDb;
using System.Threading;
using FlexCel.Core;
using FlexCel.XlsAdapter;
using FlexCel.Report;
namespace GenericReports
{
/// <summary>
/// A generic report.
/// </summary>
public partial class mainForm: System.Windows.Forms.Form
{
private EnterSQLDialog SqlDialog;
public mainForm()
{
InitializeComponent();
ResizeToolbar(mainToolbar);
}
private void ResizeToolbar(ToolStrip toolbar)
{
using (Graphics gr = CreateGraphics())
{
double xFactor = gr.DpiX / 96.0;
double yFactor = gr.DpiY / 96.0;
toolbar.ImageScalingSize = new Size((int)(24 * xFactor), (int)(24 * yFactor));
toolbar.Width = 0; //force a recalc of the buttons.
}
}
private void button2_Click(object sender, System.EventArgs e)
{
Close();
}
private void btnOpenconnection_Click(object sender, System.EventArgs e)
{
string DataPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
string ConfigFile = DataPath + "GenericReports.udl";
if (!File.Exists(ConfigFile))
using (FileStream f = File.Create(ConfigFile))
{
//Nothing, create an empty udl.
}
using (Process p = new Process())
{
p.StartInfo.FileName = ConfigFile;
p.StartInfo.UseShellExecute = true;
p.Start();
}
}
private void btnQuery_Click(object sender, System.EventArgs e)
{
string DataPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
string ConfigFile = DataPath + "GenericReports.udl";
Connection.Close();
dataSet = new DataSet();
Connection.ConnectionString = "File Name = " + ConfigFile;
Connection.Open();
if (SqlDialog == null) SqlDialog = new EnterSQLDialog();
if (SqlDialog.ShowDialog() != DialogResult.OK)
return;
dbDataAdapter.SelectCommand = new OleDbCommand(SqlDialog.SQL, Connection);
dbDataAdapter.Fill(dataSet, "Table");
dataGrid.CaptionText = dbDataAdapter.SelectCommand.CommandText;
dataGrid.SetDataBinding(dataSet, "Table");
}
private void Export(string SQL, out string DataPath)
{
Report.ClearTables();
Report.AddTable(dataSet);
Report.SetValue("Date", DateTime.Now);
Report.SetValue("ReportCaption", SQL);
DataPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar; //First try to find the template on exe folder.
if (!File.Exists(DataPath + "Generic Reports.template.xls")) //When on design mode, search for the template 2 folders up.
DataPath = Path.Combine(DataPath, Path.Combine("..", "..")) + Path.DirectorySeparatorChar;
}
private void btnExportExcel_Click(object sender, System.EventArgs e)
{
string DataPath = null;
if (dbDataAdapter == null || dbDataAdapter.SelectCommand == null || dbDataAdapter.SelectCommand.CommandText == null)
{
MessageBox.Show("You need to select a query first");
return;
}
Export(dbDataAdapter.SelectCommand.CommandText, out DataPath);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Report.Run(DataPath + "Generic Reports.template.xls", 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();
}
}
}
}
}
}
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 System.Data.OleDb;
using System.Threading;
using FlexCel.Core;
using FlexCel.XlsAdapter;
using FlexCel.Report;
namespace GenericReports
{
public partial class mainForm: System.Windows.Forms.Form
{
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Data.DataSet dataSet;
private System.Windows.Forms.DataGrid dataGrid;
private System.Data.OleDb.OleDbConnection Connection;
private System.Data.OleDb.OleDbDataAdapter dbDataAdapter;
private FlexCel.Report.FlexCelReport Report;
private System.ComponentModel.IContainer 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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(mainForm));
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.Report = new FlexCel.Report.FlexCelReport();
this.Connection = new System.Data.OleDb.OleDbConnection();
this.dataSet = new System.Data.DataSet();
this.dataGrid = new System.Windows.Forms.DataGrid();
this.dbDataAdapter = new System.Data.OleDb.OleDbDataAdapter();
this.mainToolbar = new System.Windows.Forms.ToolStrip();
this.btnOpenConnection = new System.Windows.Forms.ToolStripButton();
this.btnQuery = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnExportExcel = new System.Windows.Forms.ToolStripButton();
this.btnExit = new System.Windows.Forms.ToolStripButton();
((System.ComponentModel.ISupportInitialize)(this.dataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataGrid)).BeginInit();
this.mainToolbar.SuspendLayout();
this.SuspendLayout();
//
// saveFileDialog1
//
this.saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All " +
"files|*.*";
this.saveFileDialog1.RestoreDirectory = true;
//
// Report
//
this.Report.AllowOverwritingFiles = true;
this.Report.DeleteEmptyBands = FlexCel.Report.TDeleteEmptyBands.ClearDataAndFormats;
this.Report.DeleteEmptyRanges = false;
//
// dataSet
//
this.dataSet.DataSetName = "NewDataSet";
this.dataSet.Locale = new System.Globalization.CultureInfo("es-ES");
//
// dataGrid
//
this.dataGrid.DataMember = "";
this.dataGrid.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid.Location = new System.Drawing.Point(0, 38);
this.dataGrid.Name = "dataGrid";
this.dataGrid.Size = new System.Drawing.Size(528, 239);
this.dataGrid.TabIndex = 4;
//
// mainToolbar
//
this.mainToolbar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnOpenConnection,
this.btnQuery,
this.toolStripSeparator1,
this.btnExportExcel,
this.btnExit});
this.mainToolbar.Location = new System.Drawing.Point(0, 0);
this.mainToolbar.Name = "mainToolbar";
this.mainToolbar.Size = new System.Drawing.Size(528, 38);
this.mainToolbar.TabIndex = 12;
this.mainToolbar.Text = "mainToolbar";
//
// btnOpenConnection
//
this.btnOpenConnection.Image = ((System.Drawing.Image)(resources.GetObject("btnOpenConnection.Image")));
this.btnOpenConnection.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnOpenConnection.Name = "btnOpenConnection";
this.btnOpenConnection.Size = new System.Drawing.Size(103, 35);
this.btnOpenConnection.Text = "Open connection";
this.btnOpenConnection.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.btnOpenConnection.Click += new System.EventHandler(this.btnOpenconnection_Click);
//
// btnQuery
//
this.btnQuery.Image = ((System.Drawing.Image)(resources.GetObject("btnQuery.Image")));
this.btnQuery.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnQuery.Name = "btnQuery";
this.btnQuery.Size = new System.Drawing.Size(70, 35);
this.btnQuery.Text = "Query Data";
this.btnQuery.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.btnQuery.Click += new System.EventHandler(this.btnQuery_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 38);
//
// btnExportExcel
//
this.btnExportExcel.Image = ((System.Drawing.Image)(resources.GetObject("btnExportExcel.Image")));
this.btnExportExcel.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnExportExcel.Name = "btnExportExcel";
this.btnExportExcel.Size = new System.Drawing.Size(87, 35);
this.btnExportExcel.Text = "Export to Excel";
this.btnExportExcel.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.btnExportExcel.Click += new System.EventHandler(this.btnExportExcel_Click);
//
// btnExit
//
this.btnExit.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.btnExit.Image = ((System.Drawing.Image)(resources.GetObject("btnExit.Image")));
this.btnExit.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(59, 35);
this.btnExit.Text = " E&xit ";
this.btnExit.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.btnExit.Click += new System.EventHandler(this.button2_Click);
//
// mainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(528, 277);
this.Controls.Add(this.dataGrid);
this.Controls.Add(this.mainToolbar);
this.Name = "mainForm";
this.Text = "Generic Reports";
((System.ComponentModel.ISupportInitialize)(this.dataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataGrid)).EndInit();
this.mainToolbar.ResumeLayout(false);
this.mainToolbar.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ToolStrip mainToolbar;
private ToolStripButton btnOpenConnection;
private ToolStripButton btnQuery;
private ToolStripSeparator toolStripSeparator1;
private ToolStripButton btnExportExcel;
private ToolStripButton btnExit;
}
}
Program.cs
using System;
using System.Windows.Forms;
using System.Threading;
namespace GenericReports
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ThreadExceptionHandler handler = new ThreadExceptionHandler();
Application.ThreadException += new ThreadExceptionEventHandler(handler.Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainForm());
}
}
internal class ThreadExceptionHandler
{
public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
try
{
DialogResult result = ShowThreadExceptionDialog(
e.Exception);
if (result == DialogResult.Abort)
Application.Exit();
}
catch
{
// Fatal error, terminate program
try
{
MessageBox.Show("Fatal Error",
"Fatal Error",
MessageBoxButtons.OK,
MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
}
///
/// Creates and displays the error message.
///
private DialogResult ShowThreadExceptionDialog(Exception ex)
{
string errorMessage =
"Unhandled Exception:\n\n" +
ex.Message + "\n\n" +
ex.GetType() +
"\n\nStack Trace:\n" +
ex.StackTrace;
return MessageBox.Show(errorMessage,
"Application Error",
MessageBoxButtons.AbortRetryIgnore,
MessageBoxIcon.Stop);
}
}
}