Rendering standalone objects (C# / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\csharp\VS2022\netframework\25.Printing and Exporting\45.Render Objects and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/csharp/VS2022/netframework/Modules/25.Printing and Exporting/45.Render Objects
Overview
While you might normally want to render a full sheet (or a range of cells), you can also use FlexCel to render specific objects in the workbook.
Concepts
This is a simple application where we periodically update a number, and use FlexCel to recalculate the formulas and render a chart of the values. While you would normally not use FlexCel this way (and it is probably better to use a separate chart package), it gives a nice tasting on FlexCel capabilities.
How to use RenderObject to render a simple object in a sheet. In this demo, we are rendering the object named "datachart".
As the chart and the calculations are defined in the spreadsheet, you can add new themes to the application or modify the existing ones by creating and modifying the xls files in the templates folders, without needing to recompile the application. You can even do it in real time. Have a template open in Excel, make changes, save, and reload the template in the application by selecting it again in the listbox. Changes will appear instantly without needing to close the main application. This technique can be quite useful to let users customize your application.
In this example, we named the chart "DataChart", so we can identify it from the application. In order to name a chart object, ctrl-click in the chart (it should show white handles, not black), and then change the name in the name box at the top left in Excel.
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 - 2025 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.24.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.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using FlexCel.Core;
using FlexCel.XlsAdapter;
using FlexCel.Render;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Text;
namespace RenderObjects
{
/// <summary>
/// An Example on how to render a chart.
/// </summary>
public partial class mainForm: System.Windows.Forms.Form
{
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.
}
}
#region Global variables
private XlsFile Xls;
private TXlsNamedRange ValueRange;
private double MinValue;
private double MaxValue;
private double StepValue;
private double ActualValue;
private int ChartIndex;
private TShapeProperties ChartProps;
#endregion
private void InitApp()
{
Xls = new XlsFile();
string TemplatePath = Path.Combine(Path.Combine(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ".."), ".."), "templates") + Path.DirectorySeparatorChar;
DirectoryInfo di = new DirectoryInfo(TemplatePath);
FileInfo[] fi = di.GetFiles("*.xls");
if (fi.Length == 0) throw new Exception("Sorry, no templates found in the templates folder.");
cbTheme.Items.Clear();
foreach (FileInfo f in fi)
{
cbTheme.Items.Add(new FileHolder(f.FullName));
}
cbTheme.SelectedIndex = 0;
}
private void LoadFile(string FileName)
{
Xls.Open(FileName);
ActualValue = 0;
ValueRange = Xls.GetNamedRange("Value", 0);
if (ValueRange == null) throw new Exception("There is no range named \"value\" in the template");
MinValue = ReadDoubleName("Minimum");
MaxValue = ReadDoubleName("Maximum");
StepValue = ReadDoubleName("Step");
ChartIndex = -1;
for (int i = 1; i <= Xls.ObjectCount; i++)
{
string ObjName = Xls.GetObjectName(i);
if (String.Compare(ObjName, "DataChart", true) == 0)
{
ChartIndex = i;
break;
}
}
if (ChartIndex < 0) throw new Exception("There is no object named \"DataChart\" in the template");
ChartProps = Xls.GetObjectProperties(ChartIndex, true);
}
private double ReadDoubleName(string Name)
{
TXlsCellRange Range = Xls.GetNamedRange(Name, 0);
if (Range == null) throw new Exception("There is no range named " + Name + " in the template");
object val = Xls.GetCellValue(Range.Top, Range.Left);
if (!(val is Double)) throw new Exception("The range named " + Name + " does not contain a number");
return (Double)val;
}
private void button2_Click(object sender, System.EventArgs e)
{
Close();
}
private void updater_Tick(object sender, System.EventArgs e)
{
try
{
ActualValue += StepValue;
if (ActualValue > MaxValue) ActualValue = MinValue;
Xls.SetCellValue(ValueRange.Top, ValueRange.Left, ActualValue);
Xls.Recalc();
if (chartBox.Image != null) chartBox.Image.Dispose();
chartBox.Image = GetChart();
}
catch (Exception ex) //We don't want any dialog popping up every second.
{
labelError.Text = ex.Message;
labelError.Dock = DockStyle.Fill;
panelError.Dock = DockStyle.Fill;
panelError.Visible = true;
updater.Enabled = false;
}
}
private Image GetChart()
{
//We could get the chart with the following command,
//but it would be fixed size. In this example we are going to be a little more complex.
//Xls.RenderObject(ChartIndex);
//A more complex way to retrieve the chart, to show how to use
//all parameters in renderobject.
TUIRectangle ImageDimensions;
TPointF Origin;
TUISize SizePixels;
//First calculate the chart dimensions without actually rendering it. This is fast.
Xls.RenderObject(ChartIndex, 96, ChartProps,
SmoothingMode.AntiAlias, InterpolationMode.HighQualityBicubic, true, false,
out Origin, out ImageDimensions, out SizePixels);
double dpi = 96; //default screen resolution
if (SizePixels.Height > 0 && SizePixels.Width > 0)
{
double AspectX = (double)chartBox.Width / SizePixels.Width;
double AspectY = (double)chartBox.Height / SizePixels.Height;
double Aspect = Math.Max(AspectX, AspectY);
//Make the dpi adjust the screen resolution and the size of the form.
dpi = (double)(96 * Aspect);
if (dpi < 20) dpi = 20;
if (dpi > 500) dpi = 500;
}
return Xls.RenderObject(ChartIndex, dpi, ChartProps,
SmoothingMode.AntiAlias, InterpolationMode.HighQualityBicubic, true, true,
out Origin, out ImageDimensions, out SizePixels);
}
private void cbTheme_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (cbTheme.SelectedItem == null) return;
LoadFile((cbTheme.SelectedItem as FileHolder).FullName);
}
private void btnRun_Click(object sender, System.EventArgs e)
{
if (Xls == null) InitApp();
updater.Enabled = true;
btnRun.Enabled = false;
btnCancel.Enabled = true;
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
updater.Enabled = false;
btnRun.Enabled = true;
btnCancel.Enabled = false;
panelError.Visible = false;
}
}
internal class FileHolder
{
internal string FullName;
private string Caption;
internal FileHolder(string aFullName)
{
FullName = aFullName;
Caption = Path.GetFileNameWithoutExtension(aFullName);
}
public override string ToString()
{
return Caption;
}
}
}
Form1.Designer.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using FlexCel.Core;
using FlexCel.XlsAdapter;
using FlexCel.Render;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Text;
namespace RenderObjects
{
public partial class mainForm: System.Windows.Forms.Form
{
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()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(mainForm));
this.panel1 = new System.Windows.Forms.Panel();
this.panelError = new System.Windows.Forms.Panel();
this.labelError = new System.Windows.Forms.Label();
this.chartBox = new System.Windows.Forms.PictureBox();
this.panel7 = new System.Windows.Forms.Panel();
this.cbTheme = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.checkBox4 = new System.Windows.Forms.CheckBox();
this.updater = new System.Windows.Forms.Timer(this.components);
this.mainToolbar = new System.Windows.Forms.ToolStrip();
this.btnRun = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnExit = new System.Windows.Forms.ToolStripButton();
this.btnCancel = new System.Windows.Forms.ToolStripButton();
this.panel1.SuspendLayout();
this.panelError.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.chartBox)).BeginInit();
this.panel7.SuspendLayout();
this.mainToolbar.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.White;
this.panel1.Controls.Add(this.panelError);
this.panel1.Controls.Add(this.chartBox);
this.panel1.Controls.Add(this.panel7);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 38);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(464, 392);
this.panel1.TabIndex = 3;
//
// panelError
//
this.panelError.Controls.Add(this.labelError);
this.panelError.Location = new System.Drawing.Point(136, 128);
this.panelError.Name = "panelError";
this.panelError.Size = new System.Drawing.Size(200, 100);
this.panelError.TabIndex = 52;
this.panelError.Visible = false;
//
// labelError
//
this.labelError.Location = new System.Drawing.Point(8, 16);
this.labelError.Name = "labelError";
this.labelError.Size = new System.Drawing.Size(100, 23);
this.labelError.TabIndex = 0;
//
// chartBox
//
this.chartBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.chartBox.Location = new System.Drawing.Point(24, 120);
this.chartBox.Name = "chartBox";
this.chartBox.Size = new System.Drawing.Size(416, 250);
this.chartBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.chartBox.TabIndex = 51;
this.chartBox.TabStop = false;
//
// panel7
//
this.panel7.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel7.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.panel7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel7.Controls.Add(this.cbTheme);
this.panel7.Controls.Add(this.label2);
this.panel7.Location = new System.Drawing.Point(16, 16);
this.panel7.Name = "panel7";
this.panel7.Size = new System.Drawing.Size(432, 72);
this.panel7.TabIndex = 44;
//
// cbTheme
//
this.cbTheme.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbTheme.Location = new System.Drawing.Point(8, 32);
this.cbTheme.Name = "cbTheme";
this.cbTheme.Size = new System.Drawing.Size(248, 21);
this.cbTheme.TabIndex = 46;
this.cbTheme.SelectedIndexChanged += new System.EventHandler(this.cbTheme_SelectedIndexChanged);
//
// label2
//
this.label2.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(8, 8);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(192, 16);
this.label2.TabIndex = 19;
this.label2.Text = "Select Theme:";
//
// checkBox4
//
this.checkBox4.Location = new System.Drawing.Point(0, 0);
this.checkBox4.Name = "checkBox4";
this.checkBox4.Size = new System.Drawing.Size(104, 24);
this.checkBox4.TabIndex = 0;
//
// updater
//
this.updater.Tick += new System.EventHandler(this.updater_Tick);
//
// mainToolbar
//
this.mainToolbar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnRun,
this.toolStripSeparator1,
this.btnExit,
this.btnCancel});
this.mainToolbar.Location = new System.Drawing.Point(0, 0);
this.mainToolbar.Name = "mainToolbar";
this.mainToolbar.Size = new System.Drawing.Size(464, 38);
this.mainToolbar.TabIndex = 11;
this.mainToolbar.Text = "toolStrip1";
//
// btnRun
//
this.btnRun.Image = ((System.Drawing.Image)(resources.GetObject("btnRun.Image")));
this.btnRun.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnRun.Name = "btnRun";
this.btnRun.Size = new System.Drawing.Size(35, 35);
this.btnRun.Text = "Run!";
this.btnRun.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 38);
//
// 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);
//
// btnCancel
//
this.btnCancel.Enabled = false;
this.btnCancel.Image = ((System.Drawing.Image)(resources.GetObject("btnCancel.Image")));
this.btnCancel.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(47, 35);
this.btnCancel.Text = "Cancel";
this.btnCancel.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// mainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(464, 430);
this.Controls.Add(this.panel1);
this.Controls.Add(this.mainToolbar);
this.MaximumSize = new System.Drawing.Size(800, 800);
this.Name = "mainForm";
this.Text = "Using FlexCel to render just a part of a spreadshet";
this.panel1.ResumeLayout(false);
this.panelError.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.chartBox)).EndInit();
this.panel7.ResumeLayout(false);
this.mainToolbar.ResumeLayout(false);
this.mainToolbar.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.CheckBox checkBox4;
private System.Windows.Forms.Panel panel7;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.PictureBox chartBox;
private System.Windows.Forms.Timer updater;
private System.Windows.Forms.ComboBox cbTheme;
private System.Windows.Forms.Panel panelError;
private System.Windows.Forms.Label labelError;
private ToolStrip mainToolbar;
private ToolStripButton btnRun;
private ToolStripSeparator toolStripSeparator1;
private ToolStripButton btnExit;
private ToolStripButton btnCancel;
}
}
Program.cs
using System;
using System.Windows.Forms;
namespace RenderObjects
{
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());
}
}
}