简体   繁体   中英

Converting Excel to JSON using c# dictionary

I am using this code to convert an Excel file into a JSON format.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var pathToExcel = @"D:\works\sample.xlsx";
            var sheetName = "sa";
            var connectionString = String.Format(@"
            Provider=Microsoft.ACE.OLEDB.12.0;
            Data Source={0};
            Extended Properties=""Excel 12.0 Xml;HDR=YES""
        ", pathToExcel);

            using (var conn = new OleDbConnection(connectionString))
            {
                conn.Open();

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


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

                    var query =
                        (from DbDataRecord row in rdr
                         select row).Select(x =>
                         {


                         Dictionary<string, object> item = new     
Dictionary<string, object>();
                         for(int i=0;i<20;i++)
                         {
                             item.Add(rdr.GetName(i), x[i]);                                

                         }
                         return item;

                         });

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

                }
            }
        }
    }
}

The requirement is that I need to create sub serialized object within the JSON. For example, if a cell has a value: "name": "abc,def", the output must be:

"name":
{
 "name1": "abc",
 "name2": "def"
}

How can I modify my code to achieve this?

try this code this will help you i hope

//dynamic item = new ExpandoObject();
Dictionary<string, object> item = new Dictionary<string, object>();
for(int i=0;i<20;i++)
{
    if(x[i].ToString().Contains(","))
    {
        Dictionary<string, object> temp = new Dictionary<string, object>()
        string[] data = x[i].ToString().Split(',');
        for(int j=0;j<data.Length;j++)
        {
            temp.Add(rdr.GetName(i)+j, data[j]);
        }
        item.Add(rdr.GetName(i), temp);
    }
    else
    {
     item.Add(rdr.GetName(i), x[i]);
     Console.WriteLine("\n");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM