C# excel转换Json

C# excel转换Json//如果要支持xlsx格式表格,请在本机电脑安装这个//http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe参考案例:https://www.cnblogs.com/fengxiang/p/3551621.html使用的时候记得…

大家好,又见面了,我是你们的朋友全栈君。

//如果要支持xlsx格式表格,请在本机电脑安装这个
//http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe

参考案例:https://www.cnblogs.com/fengxiang/p/3551621.html

使用的时候记得注册AccessDatabaseEngine,该驱动有64位、32位两个版本,请根据自己的环境选择正确的版本。

需求:有大量的数据源来自Excel,需要转成JSON供程序读取使用

假如我的Excel数据如下:

C# excel转换Json

这里我们用到了Newtonsoft.Json,Newtonsoft.Json是.NET下开源的JSON格式序列化和反序列化的类库。其中Newtonsoft.Json.Linq提供了对LINQ支持,支持动态对象、数组的序列化。JArray和JObject是Newtonsoft.Json中的对象,支持动态属性和方法,表名和列名就是这样插入JSON中的。

将整个Excel转换为一个JSON文件,每一个Sheet Name作为Key,Content就是Value,Value以数组形式存在,最终得到数据格式如下:

 

 

C# excel转换Json

为了减少前后端传输数据的流量,可以使用ToString(Formatting.None),这样生成出来的数据就没有格式了。

C# excel转换Json

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.OleDb;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace ExcelTool
{
    public class ExcelHelper
    {
        /// <summary>
        /// 获取excel的DataTable
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static DataTable GetExcelContent(String filePath, string sheetName)
        {
            if (sheetName == "_xlnm#_FilterDatabase")
                return null;
            DataSet dateSet = new DataSet();
            String connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=NO;IMEX=1;'", filePath);
            String commandString = string.Format("SELECT * FROM [{0}$]", sheetName);
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                using (OleDbCommand command = new OleDbCommand(commandString, connection))
                {
                    OleDbCommand objCmd = new OleDbCommand(commandString, connection);
                    OleDbDataAdapter myData = new OleDbDataAdapter(commandString, connection);
                    myData.Fill(dateSet, sheetName);
                    DataTable table = dateSet.Tables[sheetName];

                    for (int i = 0; i < table.Rows[0].ItemArray.Length; i++)
                    {
                        var cloumnName = table.Rows[0].ItemArray[i].ToString();
                        if (!string.IsNullOrEmpty(cloumnName))
                            table.Columns[i].ColumnName = cloumnName;
                    }
                    table.Rows.RemoveAt(0);
                    return table;
                }
            }
        }

        /// <summary>
        /// 获取excel文件里面的所有的工作表名称
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static List<string> GetExcelSheetNames(string filePath)
        {
            OleDbConnection connection = null;
            System.Data.DataTable dt = null;
            try
            {
                String connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=1;'", filePath);
                connection = new OleDbConnection(connectionString);
                connection.Open();
                dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if (dt == null)
                {
                    return new List<string>();
                }

                String[] excelSheets = new String[dt.Rows.Count];
                int i = 0;
                foreach (DataRow row in dt.Rows)
                {
                    excelSheets[i] = row["TABLE_NAME"].ToString().Split('$')[0];
                    i++;
                }
                return excelSheets.Distinct().ToList();
            }
            catch (Exception ex)
            {
               // LogHelper.Logger.Error(ex);
                return new List<string>();
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                    connection.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }

        /// <summary>
        /// excel转换为json
        /// </summary>
        /// <param name="filePath"></param>
       public static void ExcelToJson(string filePath)
        {
            List<string> tableNames = ExcelHelper.GetExcelSheetNames(filePath);
            var json = new JObject();
            tableNames.ForEach(tableName =>
            {
                var table = new JArray() as dynamic;
                DataTable dataTable = ExcelHelper.GetExcelContent(filePath, tableName);
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    dynamic row = new JObject();
                    foreach (DataColumn column in dataTable.Columns)
                    {
                        row.Add(column.ColumnName, dataRow[column.ColumnName].ToString());
                    }
                    table.Add(row);
                }
                json.Add(tableName, table);
            });
            Console.WriteLine(json.ToString());
            Console.WriteLine(json.ToString(Formatting.None));
        }
    }
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/132085.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

  • Python 词频统计

    Python 词频统计

  • python 学习记录一

    python 学习记录一

  • 单例模式 指令重排_php单例模式

    单例模式 指令重排_php单例模式单例模式写法有很多,于是我看到了这么一种写法:publicclassSingletonTest{privateSingletonTest(){}privatestaticSingletonTestsingletonTest=null;publicstaticSingletonTestgetSingletonTest()…

    2022年10月17日
  • C++ char 转 int[通俗易懂]

    C++ char 转 int[通俗易懂]charcc[20]=”-100″;intdd;dd=atoi(cc);

  • 剑指offer Java_工程图学基础知识点总结

    剑指offer Java_工程图学基础知识点总结线程池顾名思义就是事先创建若干个可执行的线程放入一个池(容器)中,需要的时候从池中获取线程不用自行创建(类似于工厂设计模式),使用完毕不需要销毁线程而是返回池中,从而减少创建和销毁线程对象的开销。设计一个动态大小的线程池,如何设计,应该有哪些方法?线程管理器(ThreadPool)用于创建并管理线程池,包括创建线程,销毁线程池,添加新任务;工作线程(PoolWorker)线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;任务接口(Task)任务队列(TaskQueue)创建线程池。…

  • matlab的meshgrid函数详解

    matlab的meshgrid函数详解函数形式[C,R]=meshgrid(c,r)初步解释首先需要明确的是参数c,r都是行向量,该函数将行向量c,r指定的域变换为数组C,R,这2个数组能用来指示有2个变量的函数和三维的图。输出数组C的每一行都是行向量c,输出数组R的每一列都是行向量r。例如我们需要形成一个二维函数,其元素是由坐标变量x和y的值的平方和。也就是f(x,y)=x^2+y^2这样的形式…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号