8

I have an Excel sheet which has a set of columns and rows with data. I want to read the complete Excel sheet data as JSON, so that later I can write the JSON to a file. How can I do this?

Sample data:

Names    RegNo    Description
ABCD     12345    DemoInfo
XYZ      67890    DemoInfo2

3 Answers 3

10

Connect to the Excel sheet via the ADO.NET OleDb provider. Then, use a JSON library for C# to generate the JSON string, and save the file. (Or use the JavascriptSerialzer, as @boades suggested).

This example uses the JSON.NET library.

using System;
using System.Linq;
using System.Data.OleDb;
using System.Data.Common;
using Newtonsoft.Json;
using System.IO;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            var pathToExcel = @"C:\path\to\excel\file.xlsx";
            var sheetName = "NameOfSheet";
            var destinationPath = @"C:\path\to\save\json\file.json";

            //Use this connection string if you have Office 2007+ drivers installed and 
            //your data is saved in a .xlsx file
            var connectionString = $@"
                Provider=Microsoft.ACE.OLEDB.12.0;
                Data Source={pathToExcel};
                Extended Properties=""Excel 12.0 Xml;HDR=YES""
            ";

            //Creating and opening a data connection to the Excel sheet 
            using (var conn=new OleDbConnection(connectionString)) {
                conn.Open();

                var cmd=conn.CreateCommand();
                cmd.CommandText = $"SELECT * FROM [{sheetName}$]";

                using (var rdr=cmd.ExecuteReader()) {

                    //LINQ query - when executed will create anonymous objects for each row
                    var query = rdr.Cast<DbDataRecord>().Select(row => new {
                        name = row[0],
                        regno = row[1],
                        description = row[2]
                    });

                    //Generates JSON from the LINQ query
                    var json = JsonConvert.SerializeObject(query);

                    //Write the file to the destination path    
                    File.WriteAllText(destinationPath, json);
                }
            }
        }
    }
}

Links:

Sign up to request clarification or add additional context in comments.

1 Comment

Note that you don't need Excel installed, you can just download the Microsoft Access Database Engine Redistributable, which at this time is available here: microsoft.com/en-gb/download/details.aspx?id=13255
2

Save it as a CSV. Then use File.ReadLines to enumerate over each line, followed by String.Split to read each column. Format the data as a JSON string and save it to a file.

Comments

2

You can give a try to http://exceldatareader.codeplex.com/ library. You must read data from excel to some object, and than convert it to json using JavaScriptSerializer

public class MyRow
{
   public string Cell1;
   public string Cell2;
   public string Cell3;
}

class Program
{
        static void Main()
        {
            var list = new List<MyRow>();
            FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

            //1. Reading from a binary Excel file ('97-2003 format; *.xls)
            IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
            //...
            //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);


            //5. Data Reader methods
            while (excelReader.Read())
            {
                   var obj = new MyRow 
                   {
                       Cell1 = excelReader.GetString(0),
                       Cell2 = excelReader.GetString(1),
                       Cell3 = excelReader.GetString(2),
                   }

                   list.Add(obj);
            }

            //6. Free resources (IExcelDataReader is IDisposable)
            excelReader.Close();
            var json = new JavaScriptSerializer().Serialize(list);
            Console.WriteLine(json);
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.