Search Results for

    Show / Hide Table of Contents

    Getting started (VB.Net / netframework)

    Note

    This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\vb\VS2022\netframework\10.API\10.GettingStarted and also at https:​//​github.​com/​tmssoftware/​TMS-​FlexCel.​NET-​demos/​tree/​master/​vb/​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.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 FlexCel.Core
    Imports FlexCel.XlsAdapter
    Imports System.IO
    Imports System.Reflection
    Namespace GettingStarted
        Partial Public Class mainForm
            Inherits System.Windows.Forms.Form
    
            ''' <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.button1 = New System.Windows.Forms.Button()
                Me.saveFileDialog1 = New System.Windows.Forms.SaveFileDialog()
                Me.label1 = New System.Windows.Forms.Label()
                Me.cbAutoOpen = New System.Windows.Forms.CheckBox()
                Me.SuspendLayout()
                ' 
                ' button1
                ' 
                Me.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom
                Me.button1.Location = New System.Drawing.Point(78, 160)
                Me.button1.Name = "button1"
                Me.button1.Size = New System.Drawing.Size(75, 23)
                Me.button1.TabIndex = 0
                Me.button1.Text = "GO!"
    '           Me.button1.Click += New System.EventHandler(Me.button1_Click)
                ' 
                ' saveFileDialog1
                ' 
                Me.saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All " & "files|*.*"
                Me.saveFileDialog1.RestoreDirectory = True
                ' 
                ' label1
                ' 
                Me.label1.Anchor = (CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
                Me.label1.BackColor = System.Drawing.Color.FromArgb((CInt((CByte(255)))), (CInt((CByte(255)))), (CInt((CByte(192)))))
                Me.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
                Me.label1.Location = New System.Drawing.Point(16, 16)
                Me.label1.Name = "label1"
                Me.label1.Size = New System.Drawing.Size(205, 80)
                Me.label1.TabIndex = 1
                Me.label1.Text = "A first demo on how to create basic things with FlexCel API."
                ' 
                ' cbAutoOpen
                ' 
                Me.cbAutoOpen.Location = New System.Drawing.Point(16, 104)
                Me.cbAutoOpen.Name = "cbAutoOpen"
                Me.cbAutoOpen.Size = New System.Drawing.Size(144, 48)
                Me.cbAutoOpen.TabIndex = 2
                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(229, 197)
                Me.Controls.Add(Me.cbAutoOpen)
                Me.Controls.Add(Me.label1)
                Me.Controls.Add(Me.button1)
                Me.Name = "mainForm"
                Me.Text = "Getting Started"
                Me.ResumeLayout(False)
    
            End Sub
            #End Region
    
            Private WithEvents button1 As System.Windows.Forms.Button
            Private saveFileDialog1 As System.Windows.Forms.SaveFileDialog
            Private label1 As System.Windows.Forms.Label
            Private cbAutoOpen As System.Windows.Forms.CheckBox
    
        End Class
    End Namespace
    

    Form1.vb

    Imports System.Collections
    Imports System.ComponentModel
    Imports FlexCel.Core
    Imports FlexCel.XlsAdapter
    Imports System.IO
    Imports System.Reflection
    Imports 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>
        Partial Public Class mainForm
            Inherits System.Windows.Forms.Form
    
            Public Sub New()
                InitializeComponent()
            End Sub
    
            Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
                Dim Xls As ExcelFile = New XlsFile(True)
                AddData(Xls)
    
                If cbAutoOpen.Checked Then
                    AutoOpen(Xls)
                Else
                    NormalOpen(Xls)
                End If
            End Sub
    
            Private Sub AddData(ByVal Xls As ExcelFile)
                '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.
                Dim AssemblyPath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
                Using Img As Image = 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)
                End Using
    
                'Add a comment on cell a2
                Xls.SetComment(2, 1, "This is 3")
    
                'Custom Format cells a2 and a3
                Dim f As TFlxFormat = 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.
                Dim XF As Integer = Xls.AddFormat(f)
    
                Xls.SetCellFormat(2, 1, XF)
                Xls.SetCellFormat(3, 1, XF)
    
                f.Rotation = 45
                f.FillPattern.Pattern = TFlxPatternStyle.Solid
                Dim XF2 As Integer = 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
    
            End Sub
    
    
            '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 Function GetLockingUser(ByVal FileName As String) As String
                Try
                    Dim xerr As New XlsFile()
                    xerr.Open(FileName)
                    Return " - File might be in use by: " & xerr.Protection.WriteAccess
                Catch
                    Return String.Empty
                End Try
            End Function
    
            Private Sub NormalOpen(ByVal Xls As ExcelFile)
                If saveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                    Try
                        Xls.Save(saveFileDialog1.FileName)
                    Catch ex As IOException '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)
                    End Try
    
                    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
    
            '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 Sub AutoOpen(ByVal Xls As ExcelFile)
                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>
            ''' <returns>The generated file as a byte array.</returns>
            Public Function WebRun() As Byte()
                Dim Xls As ExcelFile = New XlsFile(True)
                AddData(Xls)
    
                Using OutStream As New MemoryStream()
                    Xls.Save(OutStream)
                    Return OutStream.ToArray()
                End Using
            End Function
    
        End Class
    End Namespace
    

    Program.vb

    Namespace GettingStarted
        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
    
    In This Article
    Back to top FlexCel Studio for the .NET Framework v7.24.0.0
    © 2002 - 2025 tmssoftware.com