[Xamarin Blog] Generate Excel Spreadsheets in Native Mobile Apps using FlexCel

MichaelBluesteinMichaelBluestein USInsider, University, Developer Group Leader ✭✭✭

Just posted: "Generate Excel Spreadsheets in Native Mobile Apps" on the Xamarin Blog.

Read the full article to learn how to use the FlexCel component to generate Excel spreadsheets from C# code in Xamarin applications.


  • JoergBattermannJoergBattermann DEMember, Beta, University

    I've been using FlexCel for a large enterprise customer of mine for the past years in a couple projects and can only say it works incredibly well and even better, their support is top-notch, too - highly recommended!

  • ErnstKuglerErnstKugler DEMember ✭✭

    is it possible to integrate pictures in the excel files???

  • Hi,
    I am FlexCel's author. First of all thanks Michael and Joerg for the comments, I appreciate them a lot! :)

    About adding images, of course you can integrate pictures into Excel files, both xls or xlsx. FlexCel has a tool, APIMate, which can help you with this kind of questions, and which you can get from:
    APIMate for OSX: http://www.tmssoftware.com/flexcel/tools/net/ApiMate.dmg
    APIMate for Windows: http://www.tmssoftware.com/flexcel/tools/net/ApiMate.zip

    Once you get APIMate, create the file in Excel, add the image, save, open the file in APIMate, and it will tell you the code you need to create the file.
    should be similar to this
    The code I get is the following:
    XlsFile xls = new XlsFile(1, true);
    using (FileStream fs = new FileStream("imagename.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    TImageProperties ImgProps = new TImageProperties();
    ImgProps.Anchor = new TClientAnchor(TFlxAnchorType.MoveAndDontResize, 2, 13, 2, 16, 13, 13, 6, 208);
    ImgProps.ShapeName = "Picture 1";
    xls.AddImage(fs, ImgProps);

    This is using the API. Using Reports, you would just drop an image in the template and name it something like "<#myimage>", then use FlexCelReport.AddValue("myImage", ByteArrayWithImage);

    You can find more information about images in reports in the example: Demo\Modules\20.Reports\65.Images
    (Note that you need to download the Windows version of FlexCel from our site to get this demo: http://www.tmssoftware.com/site/flexcelnet.asp If you are trying, instal the trial, if you buy in the component store, you get also a license to Windows FlexCel too, and you can get it from the registered users component in our page)

    A final note: You specify an image in Excel by specifying the starting cell, the offset to the starting cell, an the ending cell and offset to the ending cell. But you can also specify image width and height. I'll paste an answer I gave in FlexCel forums last week about image aspect ratios that might be useful here:

    Basically, you need to use the constructor of TClientAnchor that takes a width and a height, and FlexCel will calculate the ending rows and columns. (Excel always needs rows and columns, so TClientAnchor needs to calculate them.

    The line should be:
    TClientAnchor imgAnchor = new TClientAnchor(TFlxAnchorType.MoveAndResize, iImageRowStart, 0, 1, 0, imgHeight, imgWidth, xls);

    Where imgHeight and imgWidth are the height an width of the image in "pixels". I wrote "pixels" in quotes because Excel doesn't deal with real pixels, but with resolution independent pixels instead. An image might have 640 pixels width, but the width in the screen will depend on the screen resolution.
    So, now having this part, how do we calculate imgHeight and imgWidth.
    You want imgWidth to be 5 columns. So you'll need to loop over all columns, sum their width, and divide by ExcelMetrics.ColMult to get the row in pixels. Then to keep the aspect ratio, imgHeight should be originalimageheight * newWidth/OriginalImageWidth
    A full working example is below:
    private double GetWidth(ExcelFile xls, int col1, int col2)
    double Result = 0;
    for (int c = col1; c < col2; c++)
    Result += xls.GetColWidth(c, true);

            return Result / ExcelMetrics.ColMult(xls);
        private void TmpButton_Click(object sender, System.EventArgs e)
            string file = "r:\\test.png";
            XlsFile xls = new XlsFile("r:\\test.xlsx", true);
            int imgColStart = 3;
            int imgColWidth = 5;
            int imgWidth = (int)(GetWidth(xls, imgColStart, imgColStart + imgColWidth));
            int imgHeight = 0;
            using (Image img = Image.FromFile(file))
                if (img.Widht > 0) imgHeight = img.Height * imgWidth / img.Width;
            int iImageRowStart = 2;
            TClientAnchor imgAnchor = new TClientAnchor(TFlxAnchorType.MoveAndResize, iImageRowStart, 0, imgColStart, 0, imgHeight, imgWidth, xls);
            xls.AddImage(file, new TImageProperties(imgAnchor, file));


  • JorgeIsaiasJorgeIsaias USMember

    Hello Adrian,

    Nice component, is it possible to create an excel file using your component from an existing populated Data base (on my app I´m using SQLite.Net)?. My App is on Xamarin.Android. I share with you a post a made asking for a component like your to complement my question.


    Thanks in advance.

  • AdrianGalleroAdrianGallero UYMember


    Yes, not only it is possible, this is what this component is mostly about. Getting data from database or business objects, and export them to Excel, csv, pdf or html.

    You have 2 ways to do it:
    1)Via only code. In this case, you would loop over the records in your dataset, and call SetCellValue() to fill an Excel file. For example, in pseudocode:

    XlsFile xls = new XlsFile(1, true);
    for (int row = 0; row < dataset.RecordCount; row++)  
       for (int col = ...)
         xls.SetCellValue(row, col, databasevalue[row, col]);

    You can do most things you want with the code, for example protect the sheet, or freeze the header row so when you scroll down it is fixed. To know how to do all this stuff, you create a file in Excel, do the things you want (for example freeze a row), and then open it in APIMate (the links for downloading APIMate for windows or OSX are in the Getting started page). APIMate will tell you the C# code you need to recreate the file you created in Excel in FlexCel.

    2)Using Reports: This works a little different, and it is nice specially when you know the fields in advance that you want to export. For example, you could create an xls/x file in Excel and write in A2: <#Customer.Name>, in B2: <#Customer.Country>, etc, and then run a report using your SQLite db to fill in the tags. The advantage of the report approach is that your user can modify the template and add columns, or freeze the header row as in the case 1), but without touching the code. They only have to modify the template. I personally know some "power users" on some of my personal apps who learn how to create templates even if they can't code, and they can get some reports that I would not know how to do them. It is great because I send them basic reports, and then they can customize them as they wish. For example if the logo of the company changed, they just edit the template and change the logo.

    For an example on how to do reports, please take a look at the "langwars" iOS demo: It reads a dataset from StackOverflow (of from a local file, depending on your settings), and then dumps it into an xls file which is later converted to html so it can be displayed in a web browser component.

    But to get more information on how to use either reports or just code, you'll need to get the trial windows version of FlexCel from here:

    There are about 50 examples which we sadly can't convert all to iOS and android, so you'll have to look at them in Windows. But they translate virtually unchanged to iOS.

    Note also that if you decide to buy either on our site or in the component store, you'll get a license that is good for iOS, Android, Windows, OSX and very soon now Windows Store 8.1 (WinRT) and Windows Phone 8.

    Well, I could keep speaking for years about this stuff, so I'll stop now :) If you have any more specific doubts, please don't hesitate to ask.

  • AltafHussainAltafHussain USMember
    edited October 2014

    hello all
    i just downloaded the trial version of FlexCel and wrote a simple code for android in xamarin

    using System;

    using Android.App;

    using Android.Content;

    using Android.Runtime;

    using Android.Views;

    using Android.Widget;

    using Android.OS;

    using FlexCel.Core;

    using FlexCel.XlsAdapter;

    using System.IO;

    namespace app7


    [Activity (Label = "app7", MainLauncher = true)]
    public class Activity1 : Activity
        XlsFile xls = new XlsFile (1, true);                         //HERE I AM GETTING ERROR
        protected override void OnCreate (Bundle bundle)
            base.OnCreate (bundle);
            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);
            // Get our button from the layout resource,
            // and attach an event to it


    i am getting this error while debugging

    System.TypeLoadException: Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'FlexCel'.
    at app7.Activity1..ctor () [0x00000] in c:\Users\Altaf\Documents\Projects\app7\app7\MainActivity.cs:18
    at at (wrapper dynamic-method) object.cf5e2a59-0515-4370-85f8-dfc1218586b1 (intptr,object[])
    at Java.Interop.TypeManager.n_Activate (intptr,intptr,intptr,intptr,intptr,intptr) [0x0006a] in /Users/builder/data/lanes/monodroid-lion-monodroid-4.6.6-branch/6d7480e9/source/monodroid/src/Mono.Android/src/Java.Interop/TypeManager.cs:141
    at at (wrapper native-to-managed) Java.Interop.TypeManager.n_Activate (intptr,intptr,intptr,intptr,intptr,intptr)

    ALSO i CHECKED "WRITE_EXTERNAL_STORAGE" under android maifest . and i tried writing and reading to txt file over same device and it works fine ,

    if u could solve my problem
    thanks in advance

  • Hi,
    Is this using the latest Xamarin Version? This error happens when you try to run a .NET 4.5 assembly with a .NET 4.0 framework:

    The latest Xamarin should have support for the 4.5 environment.

  • AltafHussainAltafHussain USMember

    is there any alternative i just need to read from excel file . if there is any other way please share ,

  • ChrisDeBrodie.OAChrisDeBrodie.OA USUniversity ✭✭

    hello how would I open a local excel document using FlexCel?

  • Hi,
    You would normally just use

    var xls = new XlsFile(PathToLocalDocument, true);

    Now, of course the question is where the local document is located, but that depends on your app, and if you are using android or iOS. If using android, you could open either an asset, an embedded resource, or a file. In iOS, you can open an embedded resource or a local file.

    Take a look at the example "LangWars" in either iOS or Android for an example of an app using a local file. It uses this line in iOS:
    ExcelFile Result = new XlsFile(Path.Combine(NSBundle.MainBundle.BundlePath, "report.template.xls"), true);

    While in Android it uses an Android Asset. Assets are a little complex to use because the streams are not seekable, so you need to copy them into a memory stream first in order to open it.

    The code used in the example is:

                ExcelFile Result = new XlsFile(true);
                using(var template = Assets.Open("report.template.xls"))
                    //we can't load directly from the asset stream, as we need a seekable stream.
                    using (var memtemplate = new MemoryStream())
                        memtemplate.Position = 0;

    But of course, you could use a local file instead of an asset. In the example "FlexCalc", we use this line in iOS:

               string FileName{ get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "FlexCalc.xls"); }}

    ant this line in Android:

            string ConfigFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "config.xls");

    and then open directly the file.

  • ChrisDeBrodie.OAChrisDeBrodie.OA USUniversity ✭✭

    i'm using iOS any thoughts on how to do this?

  • ChrisDeBrodie.OAChrisDeBrodie.OA USUniversity ✭✭
    edited February 2016

    @AdrianGallero this is what my code looks like:

    using FlexCel.Core;
    using FlexCel.XlsAdapter;
    using Foundation;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    using UIKit;
    namespace Justice_Compliance_Monitoring_App
        partial class SurveyView : UIViewController
            public SurveyView(IntPtr handle)
                : base(handle)
            public override void ViewDidLoad()
                ExcelFile Result = new XlsFile(Path.Combine(NSBundle.MainBundle.BundlePath, "Survey.xlsx"), true);
                //var xls = new XlsFile("Survey.xlsx", true);

    it opens the app up but nothing shows what am I doing wrong?

  • Hi,
    I think you are misunderstanding what FlexCel does. FlexCel is not a grid control, and it is non visual. It allows you to read and write xls/x files from your app, but it won't show them in a grid.

    The code you posted will load the file into memory, but that's it. You could add some lines like:
    Result.SetCellValue(1, 1, "hi");
    Result.Save(Path.Combine(NSBundle.MainBundle.BundlePath, "Survey2.xlsx"));

    And you could then share the generated file with some other app, for example. You could also convert the file to pdf and display it in a WebBrowser control, but it would be display only. I think you are looking more for a control where you get a grid which the user can modify, but this is not what FlexCel does.

  • hi Adrian, I have been trying to convert an excel file to pdf / html, i get an exception "Missing method exception - Method 'String.Format' not found." Stack trace is given below.

    at FlexCel.Render.MediaRange.IsFromAssembly (FlexCel.Core.ExcelFile TimeMinutes, FlexCel.Render.MixinMatch BaseURI, FlexCel.Render.MethodExpr EventCategory, System.String NodeValue, Boolean AString, Int32 TextBackground, FlexCel.Core.TShapeProperties Descriptor) [0x00052] in :0
    at FlexCel.Render.MediaRange.PrintBoolean (FlexCel.Core.ExcelFile RootNamespace, FlexCel.Render.MixinMatch AThing, FlexCel.Render.MethodExpr ValueString, System.String CurrentResults, Boolean SelectedFont) [0x0007b] in :0
    at FlexCel.Render.MediaRange.GetLong (FlexCel.Core.ExcelFile IsPointer, FlexCel.Render.MixinMatch AllValues, FlexCel.Render.MethodExpr IsSslRequired, System.String Advanced, Boolean SourceTypeID) [0x0003b] in :0
    at FlexCel.Render.FlexCelHtmlExport.SimpleParseAt (FlexCel.Core.ExcelFile Permissions, FlexCel.Render.MethodExpr SpriteList, FlexCel.Render.TCssInformation RChevronToken, FlexCel.Core.TXlsCellRange[] IsInteger, FlexCel.Core.TMimeWriter SourceVersion, System.String EndCharacters, FlexCel.Render.TSheetSelector PropertyMapped) [0x000d9] in :0
    at FlexCel.Render.FlexCelHtmlExport.DeleteStream (FlexCel.Core.ExcelFile ReferenceList, FlexCel.Render.MethodExpr LevelOrdinal, FlexCel.Render.TCssInformation IsIterator, FlexCel.Core.TMimeWriter OldProxy, System.String HandlerDef, FlexCel.Render.TSheetSelector KeyVals, Boolean RoundingMode) [0x00018] in :0
    at FlexCel.Render.FlexCelHtmlExport.DropIndex (System.String AboutMe, System.String DomainWildcard, FlexCel.Render.TCssInformation PropertyB, FlexCel.Render.TSheetSelector IsInvalid) [0x0002a] in :0

  • Hi,
    Is this happening in Android or iOS (or both?). Which Xamarin version?

  • vini001vini001 INMember

    @AdrianGallero Is it possibile to create excel files in xamarin.android?l would like to load database data from sql server and load it into excel sheet which i have created.

  • Hi,
    Yes, android is fully supported, and you can create both Excel files or pdf files on it. Take a look at the android demos that come with the component.

  • vini001vini001 INMember

    @AdrianGallero Thank you for the reply.l tried with the sample code which you provided.But i am getting some error as
    System.TypeLoadException: Could not load type 'Microsoft.Win32.UserPreferenceChangingEventHandler' from assembly 'System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'..

    The sample code which i tried to save excel fie is

    string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
    var dbPath = System.IO.Path.Combine(documentsPath, "cloud1.xls");
    XlsFile xls = new XlsFile(1, TExcelFileFormat.v2016, true);
    xls.SetCellValue(1, 1, "Hi");
    //xls.SetCellValue(2, 1, 7);
    //xls.SetCellValue(3, 1, 11);
    //xls.SetCellValue(4, 1, new TFormula("=Sum(A2:A3)"));

    Can u please help me to solve it

  • Hi,
    Are you using the Android Assembly from here:

    Note that FlexCel comes with different dlls for android, ios, windows, etc, and you need to use the correct one. We provide portable dlls for windows phone/RT, but those won't work with ios, android, etc. (because we use a lot of platform specific stuff, coregraphics in ios, skia in android)

    From the message you are getting (failing to load a win32 assembly) it looks as if you were trying to use the windows FlexCel dll in android. So before going further, can you confirm you are using the android FlexCel.dll?

  • vini001vini001 INMember

    Yea.l have downladed from the same website which u mentioned above.same problem exists.

  • I don't really know what can be happening. I've tried it here with a new Android app, downloading the component from the app store just to be 100% sure, and it worked as expected. I tried it with:

    Xamarin Studio Community
    Version 6.1.1 (build 15)
    Installation UUID: b6190046-ca41-4354-b58f-75fe403942a0
    Mono 4.6.1 (mono-4.6.0-branch-c8sr0/ef43c15) (64-bit)
    GTK+ 2.24.23 (Raleigh theme)

    Package version: 406010005

    Version: (Xamarin Studio Community)
    Android SDK: /Users/adrian/Library/Developer/Xamarin/android-sdk-macosx
    Supported Android versions:
    2.3 (API level 10)
    4.0.3 (API level 15)
    4.4 (API level 19)
    6.0 (API level 23)

    And compiled for Android Marshmallow. What setup are you using, so I can try it here?
    Also, can you send me the test app you are using to adrian@tmssoftware.com so I can try it here?
    I really can't imagine why you would get an error with a Win32 assembly not found.

Sign In or Register to comment.