Table of Contents

Getting started (C# / netframework)

Note

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

Overview

A simple demo showing how to create an Excel file with the API from scratch.

Concepts

  • Before using FlexCel, you have to add it to the references, and add "using FlexCel.Core" and "using FlexCel.XlsAdapter" to your using statements.

  • The most important class here is the XlsFile class, from where you can read and write to any Excel 2 or newer file.

  • To set the value for a cell, use XlsFile.SetCellValue. You can set any kind of object here, not just text. If you set it to a TFormula object, you will enter a formula.

  • As explained in the FlexCel API Developer Guide, formats in Excel are indexes to an XF (eXtended Format list) To modify the format on a cell, you have to assign an XF index to that cell. To create new XF formats, use XlsFile.AddFormat

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.25.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 FlexCel.Core;
using FlexCel.XlsAdapter;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Threading;

namespace GettingStarted
{
    /// <summary>
    /// A small example on how to create a simple file with the API.
    /// Note that you can use the APIMate tool (in Start Menu->TMS FlexCel Studio->Tools) to find out the 
    /// methods you need to call.
    /// </summary>
    public partial class mainForm: System.Windows.Forms.Form
    {

        public mainForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            ExcelFile Xls = new XlsFile(true);
            AddData(Xls);

            if (cbAutoOpen.Checked)
                AutoOpen(Xls);
            else
                NormalOpen(Xls);
        }

        private void AddData(ExcelFile Xls)
        {
            //Create a new file. We could also open an existing file with Xls.Open
            Xls.NewFile(1, TExcelFileFormat.v2019);
            //Set some cell values.
            Xls.SetCellValue(1, 1, "Hello to the world");
            Xls.SetCellValue(2, 1, 3);
            Xls.SetCellValue(3, 1, 2.1);
            Xls.SetCellValue(4, 1, new TFormula("=Sum(A2,A3)"));

            //Load an image from disk.
            string AssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            using (Image Img = Image.FromFile(AssemblyPath + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + "Test.bmp"))
            {

                //Add a new image on cell E2
                Xls.AddImage(2, 6, Img);
                //Add a new image with custom properties at cell F6
                Xls.AddImage(Img, new TImageProperties(new TClientAnchor(TFlxAnchorType.DontMoveAndDontResize, 2, 10, 6, 10, 100, 100, Xls), ""));
                //Swap the order of the images. it is not really necessary here, we could have loaded them on the inverse order.
                Xls.BringToFront(1);
            }

            //Add a comment on cell a2
            Xls.SetComment(2, 1, "This is 3");

            //Custom Format cells a2 and a3
            TFlxFormat f = Xls.GetDefaultFormat;
            f.Font.Name = "Times New Roman";
            f.Font.Color = Color.Red;
            f.FillPattern.Pattern = TFlxPatternStyle.LightDown;
            f.FillPattern.FgColor = Color.Blue;
            f.FillPattern.BgColor = Color.White;

            //You can call AddFormat as many times as you want, it will never add a format twice.
            //But if you know the format you are going to use, you can get some extra CPU cycles by
            //calling addformat once and saving the result into a variable.
            int XF = Xls.AddFormat(f);

            Xls.SetCellFormat(2, 1, XF);
            Xls.SetCellFormat(3, 1, XF);

            f.Rotation = 45;
            f.FillPattern.Pattern = TFlxPatternStyle.Solid;
            int XF2 = Xls.AddFormat(f);
            //Apply a custom format to all the row.
            Xls.SetRowFormat(1, XF2);

            //Merge cells
            Xls.MergeCells(5, 1, 10, 6);
            //Note how this one merges with the previous range, creating a final range (5,1,15,6)
            Xls.MergeCells(10, 6, 15, 6);


            //Make the page print in landscape or portrait mode
            Xls.PrintLandscape = false;  

        }


        //This is part of an advanced feature (showing the user using a file) , you do not need to use
        //this method on normal places.
        private string GetLockingUser(string FileName)
        {
            try
            {
                XlsFile xerr = new XlsFile();
                xerr.Open(FileName);
                return " - File might be in use by: " + xerr.Protection.WriteAccess;
            }
            catch
            {
                return String.Empty;
            }
        }

        private static void LaunchFile(string f)
        {
            if (f != null)
            {
                using (Process p = new Process())
                {               
                    p.StartInfo.FileName = f;
                    p.StartInfo.UseShellExecute = true;
                    p.Start();
                }              
            }            
        }

        private void NormalOpen(ExcelFile Xls)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Xls.Save(saveFileDialog1.FileName);
                }
                catch (IOException ex) //This is not really needed, just to show the username of the user locking the file.
                {
                    throw new IOException(ex.Message + GetLockingUser(saveFileDialog1.FileName), ex);
                }

                if (MessageBox.Show("Do you want to open the generated file?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    LaunchFile(saveFileDialog1.FileName);
                }
            }
        }

        //This method will use a "trick" to create a temporary file and delete it even when it is open on Excel.
        //We will create a "template" (xlt/x file), and tell Excel to create a new file based on this template.
        //Then we can safely delete the xlt/x file, since Excel opened a copy.
        private void AutoOpen(ExcelFile 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);
                }
                LaunchFile(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
                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>
        /// <returns>The generated file as a byte array.</returns>
        public byte[] WebRun()
        {
            ExcelFile Xls = new XlsFile(true);
            AddData(Xls);

            using (MemoryStream OutStream = new MemoryStream())
            {
                Xls.Save(OutStream);
                return OutStream.ToArray();
            }
        }

    }
}

Form1.Designer.cs

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using FlexCel.Core;
using FlexCel.XlsAdapter;
using System.IO;
using System.Diagnostics;
using System.Reflection;
namespace GettingStarted
{
    public partial class mainForm: System.Windows.Forms.Form
    {
        /// <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.button1 = new System.Windows.Forms.Button();
            this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            this.label1 = new System.Windows.Forms.Label();
            this.cbAutoOpen = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.button1.Location = new System.Drawing.Point(78, 160);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "GO!";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // saveFileDialog1
            // 
            this.saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All " +
    "files|*.*";
            this.saveFileDialog1.RestoreDirectory = true;
            // 
            // label1
            // 
            this.label1.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.label1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label1.Location = new System.Drawing.Point(16, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(205, 80);
            this.label1.TabIndex = 1;
            this.label1.Text = "A first demo on how to create basic things with FlexCel API.";
            // 
            // cbAutoOpen
            // 
            this.cbAutoOpen.Location = new System.Drawing.Point(16, 104);
            this.cbAutoOpen.Name = "cbAutoOpen";
            this.cbAutoOpen.Size = new System.Drawing.Size(144, 48);
            this.cbAutoOpen.TabIndex = 2;
            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(229, 197);
            this.Controls.Add(this.cbAutoOpen);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button1);
            this.Name = "mainForm";
            this.Text = "Getting Started";
            this.ResumeLayout(false);

        }
        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.SaveFileDialog saveFileDialog1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.CheckBox cbAutoOpen;

    }
}


Program.cs

using System;
using System.Windows.Forms;

namespace GettingStarted
{
    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());
        }
    }
}