4 Easy Steps to Export Excel Files to JSON Using C# | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (172).NET Core  (29).NET MAUI  (192)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (209)BoldSign  (12)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (63)Flutter  (131)JavaScript  (219)Microsoft  (118)PDF  (80)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (882)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (49)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (125)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (62)Development  (613)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (37)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (488)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (41)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (368)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (30)Visual Studio Code  (17)Web  (577)What's new  (313)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
4 Easy Steps to Export Excel Files to JSON Using C#

4 Easy Steps to Export Excel Files to JSON Using C#

Syncfusion Excel (XlsIO) Library is a .NET Excel library that allows users to convert Excel documents to various file formats such as PDF, image, HTML, ODS, and JSON. Among them, the Excel-to-JSON conversion is supported from the 18.3 version onward. The resultant JSON files can be bound to any control in any platform. This is one of the major advantages for users.

Enjoy a smooth experience with Syncfusion’s Excel Library! Get started with a few lines of code and without Microsoft or interop dependencies.

In this blog, we are going to see how an Excel file can be converted to a JSON stream in C# using the Syncfusion XlsIO library. We’ll also look at the procedure to bind the JSON stream to a Syncfusion DataGrid control. The following options are available in the Excel to JSON conversion:

  • Excel workbook to a JSON file.
  • Excel worksheet to a JSON file.
  • Excel worksheet ranges to a JSON file.

The following screenshot shows the input template to be converted into a JSON stream.

Input template document
Input template document

Steps to export Excel data to JSON format

Let’s see how to convert an Excel file to a JSON stream and display the JSON stream in a data grid in an ASP.NET Core web application.

Step 1: Create an ASP.NET Core project.

Step 2: Install the following NuGet packages as references to your .NET Core applications from NuGet.org:

Step 3: Add the following code example in the index.cshtml file to design the UI screen.

@{
    ViewData["Title"] = "Home Page";
}

<div class="Common">
    @{ Html.BeginForm("Index", "Home", FormMethod.Post);

    <div class="tablediv">
        <div class="rowdiv">
            <p style="font-weight:normal">
                Click the "Input Template" button to view the input Excel document. Please note that the Microsoft Excel viewer or Microsoft Excel is required to view the Excel document.
            </p>
            <p style="font-weight:normal">
                Click the "Convert to JSON" button to view the JSON data.
            </p>
        </div>
        <br />
    </div>
    <div class="rowdiv">
        <div class="celldiv">
            <label style="font-weight:normal">
                Convert
            </label>
               
            <select name="ConvertOptions" id="convertOption" style="width:120px;">
                <option>Workbook</option>
                <option>Worksheet</option>
                <option>Range</option>
            </select>
        </div>
        <br />
    </div>
    <div>        
        <ejs-tab id="ej2Tab">
            <e-tab-tabitems>
                <e-tab-tabitem >
                    <e-content-template>
                        <div>
                            <div class="e-tab-header">
                                <div>Sheet1</div>
                                <div>Sheet2</div>
                            </div>
                            <div class="e-content">
                                <div>
                                    <ejs-grid id="Sheet1" dataSource="@ViewBag.Tab1" height="250" width="900">
                                        <e-grid-columns>
                                            <e-grid-column field="Category" headerText="Category" width="120"></e-grid-column>
                                            <e-grid-column field="Category Detail" headerText="Category Detail" textAlign="Left" width="150"></e-grid-column>
                                            <e-grid-column field="Title(s)" headerText="Title(s)" width="150"></e-grid-column>
                                            <e-grid-column field="Firm Name" headerText="Firm Name" textAlign="Left" width="150"></e-grid-column>
                                            <e-grid-column field="Client" headerText="Client" textAlign="Left" width="100"></e-grid-column>
                                            <e-grid-column field="Award" headerText="Award" width="100"></e-grid-column>
                                        </e-grid-columns>
                                    </ejs-grid>
                                </div>
                                <div>
                                    <div>
                                        <ejs-grid id="Sheet2" dataSource="@ViewBag.Tab2" height="250" width="900">

                                            <e-grid-columns>
                                                <e-grid-column field="Date" headerText="Date" textAlign="Left" width="120"></e-grid-column>
                                                <e-grid-column field="Region" headerText="Region" textAlign="Left" width="150"></e-grid-column>
                                                <e-grid-column field="Employee" headerText="Employee" width="150"></e-grid-column>
                                                <e-grid-column field="Item" headerText="Item" textAlign="Left" width="150"></e-grid-column>
                                                <e-grid-column field="Units" headerText="Units" textAlign="Left" width="100"></e-grid-column>
                                                <e-grid-column field="Unit Cost" headerText="Unit Cost" width="100"></e-grid-column>
                                                <e-grid-column field="Total" headerText="Total" textAlign="Left" width="150"></e-grid-column>
                                            </e-grid-columns>
                                        </ejs-grid>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </e-content-template>
                </e-tab-tabitem>
            </e-tab-tabitems>
        </ejs-tab>
    </div>
    <br/>
    <div class="rowdiv">
        <div class="celldiv">
            <input id="inputTemplate" class="e-btn" type="submit" name="button" value="Input Template" style="width:150px;" />
               
            <input id="convertToJSON" class="e-btn" type="submit" name="button" value="Convert to JSON" style="width:150px;" />
        </div>
    </div>
    }
</div>

<script>
    var GridData =@Html.Raw( @Json.Serialize(ViewBag.data));
function load() {
    var grid = document.getElementById('Grid').ej2_instances[0];
    grid.dataSource = GridData;
}
</script>

That code example contains the following components:

  • ComboBox: To choose to convert the entire workbook to a JSON file, or a particular worksheet to a JSON file, or a specific range of worksheets to a JSON file.
    Combo Box
  • DataGrid: To display the JSON data that is converted from the Excel file.

    JSON data bound to DataGrid
    JSON data bound to DataGrid
  • Input Template button: To download the input Excel file.
  • Convert to JSON button: To convert the input Excel file to a JSON file.

This code will create a webpage, as shown in the following image.

The UI design of the example
The UI design of the example

Immerse yourself in practical examples spotlighting the extraordinary features of Syncfusion’s C# Excel Library!

Step 4: Click Convert to JSON. The input Excel document will be converted to a JSON stream according to the option selected (workbook, worksheet, or range) in the combo box. Then, the converted JSON data will be bound to the DataGrid created on the webpage.

The following is the code written in the HomeController.cs class.

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Syncfusion.EJ2.Navigations;
using Syncfusion.XlsIO;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Text;

namespace Excel_JSON_Grid.Controllers
{
    public class HomeController : Controller
    {
        IHostingEnvironment _env;
        public HomeController(IHostingEnvironment env)
        {
            _env = env;
        }
        public IActionResult Index(string button, string ConvertOptions)
        {
            ViewBag.Sheet1 = new TabHeader { Text = "Sheet1" };
            ViewBag.Sheet2 = new TabHeader { Text = "Sheet2" };
            if (button == null)
                return View();
            else if (button == "Input Template")
            {
                //Instantiate the spreadsheet creation engine.
                ExcelEngine excelEngine = new ExcelEngine();

                //Instantiate the Excel application object.
                IApplication application = excelEngine.Excel;
                application.DefaultVersion = ExcelVersion.Xlsx;

                //Load the input Excel file.
                FileStream stream = new FileStream(_env.WebRootPath + "\\ExcelToJSON.xlsx", FileMode.Open, FileAccess.ReadWrite);
                IWorkbook workbook = application.Workbooks.Open(stream);
                stream.Close();

                //Save the input Excel file to a stream.
                MemoryStream ms = new MemoryStream();
                workbook.SaveAs(ms);
                ms.Position = 0;

                excelEngine.Dispose();

                string contentType = "Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                string fileName = "Sample.xlsx";

                //Return the input Excel file stream.
                return File(ms, contentType, fileName);
            }
            else
            {
                //Instantiate the spreadsheet creation engine.
                ExcelEngine excelEngine = new ExcelEngine();

                //Instantiate the Excel application object.
                IApplication application = excelEngine.Excel;
                application.DefaultVersion = ExcelVersion.Xlsx;

                //Load the input Excel file.
                FileStream stream = new FileStream(_env.WebRootPath + "\\ExcelToJSON.xlsx", FileMode.Open, FileAccess.ReadWrite);
                IWorkbook book = application.Workbooks.Open(stream);
                stream.Close();

                //Access first worksheet.
                IWorksheet worksheet = book.Worksheets[0];
                
                //Access a range.
                IRange range = worksheet.Range["A1:H10"];

                MemoryStream jsonStream = new MemoryStream();

                if (ConvertOptions == "Workbook")
                    book.SaveAsJson(jsonStream); //Save the entire workbook as a JSON stream.
                else if (ConvertOptions == "Worksheet")
                    book.SaveAsJson(jsonStream, worksheet); //Save the first worksheet as a JSON stream.
                else if (ConvertOptions == "Range")
                    book.SaveAsJson(jsonStream, range); //Save the range as JSON stream.

                excelEngine.Dispose();

                byte[] json = new byte[jsonStream.Length];

                //Read the JSON stream and convert to a JSON object.
                jsonStream.Position = 0;
                jsonStream.Read(json, 0, (int)jsonStream.Length);
                string jsonString = Encoding.UTF8.GetString(json);
                JObject jsonObject = JObject.Parse(jsonString);

                //Bind the converted JSON object to the DataGrid.
                if (ConvertOptions == "Workbook")
                {
                    //The first worksheet in the input document is converted to a JSON stream and bound to the DataGrid in the first tab.
                    ViewBag.Tab1 = ((JArray)(jsonObject["Sheet1"])).ToObject<List<CustomDynamicObject>>();

                    //The second worksheet in the input document is converted to a JSON stream and bound to the DataGrid in the second tab.
                    ViewBag.Tab2 = ((JArray)(jsonObject["Sheet2"])).ToObject<List<CustomDynamicObject>>();

                    return View();
                }
                else if (ConvertOptions == "Worksheet" || ConvertOptions == "Range")
                {
                    ViewBag.Tab1 = ((JArray)(jsonObject["Sheet1"])).ToObject<List<CustomDynamicObject>>();
                    ViewBag.Tab2.Visible = false;
                }

                jsonStream.Position = 0;

                return View();
            }
        }
    }

    #region Helper Classes
    /// <summary>
    /// Custom dynamic object class.
    /// </summary>
    public class CustomDynamicObject : DynamicObject
    {
        /// <summary>
        /// The dictionary property used to store the data.
        /// </summary>
        internal Dictionary<string, object> properties = new Dictionary<string, object>();
        /// <summary>
        /// Provides the implementation for operations that get member values.
        /// </summary>
        /// <param name="binder">Get Member Binder object</param>
        /// <param name="result">The result of the get operation.</param>
        /// <returns>true if the operation is successful; otherwise, false.</returns>
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = default(object);

            if (properties.ContainsKey(binder.Name))
            {
                result = properties[binder.Name];
                return true;
            }
            return false;
        }
        /// <summary>
        /// Provides the implementation for operations that set member values.
        /// </summary>
        /// <param name="binder">Set memeber binder object</param>
        /// <param name="value">The value to set to the member</param>
        /// <returns>true if the operation is successful; otherwise, false.</returns>
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            properties[binder.Name] = value;
            return true;
        }
        /// <summary>
        /// Return all dynamic member names.
        /// </summary>
        /// <returns>the property name list</returns>
        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return properties.Keys;
        }
    }
    #endregion
}

After executing this code example, we will get output like in the following screenshot. The entire Excel workbook is converted into a JSON stream, the data is displayed in the DataGrid, and each worksheet is shown in separate tabs.

Excel document converted to JSON stream and bound to the DataGrid
Excel document converted to JSON stream and bound to the DataGrid

GitHub samples

You can download the complete source code of this example from this GitHub link.

Don't settle for ordinary spreadsheet solutions. Switch to Syncfusion and upgrade the way you handle Excel files in your apps!

Wrapping up

As you can see, Syncfusion Excel (XlsIO) Library provides support to convert Excel documents to JSON in C#. You can do this easily by following the steps given in this blog. Take a moment to peruse our documentation, where you’ll find info on other conversions, like Excel-to-PDFExcel-to-HTML, worksheet-to-imageExcel-to-CSV, and Excel-to-ODS, all with accompanying code samples.

Using the XlsIO library, you can also export Excel data to data tables, TSV, collections of objects, and many more file formats.

If you are new to our Excel Library, we highly recommend you follow our Getting Started guide.

Are you already a Syncfusion user? You can download the product setup here. If you’re not yet a Syncfusion user, you can download a free 30-day trial here.

If you have any questions about these features, please let us know in the comments section below. You can also contact us through our support forum, support portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed
Scroll To Top