最近在做一个火炬之光的技能系统的demo,需要用到配置表工具。

&在网上没有找到让自己满意的工具&自己感兴趣,

so自己做了一个。

我使用的C#语言,用了网上的SimpleJSON工具脚本来做的,下面直接上代码:

界面代码(ps.注释掉的部分是生成对应代码的类,但感觉目前写的不好,就不上传了。。。)

 using System;
 using System.Collections.Generic;
 using System.Windows.Forms;

 namespace ConfigTool
 {
     public partial class Form1 : Form
     {
         private string excelPath;
         private string jsonPath;
         private string codePath;

         public Form1()
         {
             InitializeComponent();
             InitPath();
         }

         private void InitPath()
         {
             excelPath = Tool. GetPath() + "ConfigExcel";
             jsonPath = Tool.GetPath() + "Assets\\Resources\\Config";
             //codePath = Tool.GetPath(5) + "Assets\\Scripts\\Config";
             folderPath.Text = excelPath;
         }

         private void createJsonAndCode_Click(object sender, EventArgs e)
         {
             ExcelToJson etoJson = new ExcelToJson(excelPath, jsonPath);
             etoJson.CreateJsonFiles();
             fileNum.Text = etoJson.GetFileCount().ToString();

             //AutoCreateCode createCode = new AutoCreateCode(codePath, etoJson.JsonDic);
             //createCode.CreateCodeFiles();
         }
     }
 }

工具代码

 using System;
 using System.IO;

 namespace ConfigTool
 {
     public static class Tool
     {
         /// <summary>
         /// 创建文件
         /// </summary>
         /// <param name="_path">文件路径(包含文件名及其后缀)</param>
         /// <param name="_content">文件存储的内容</param>
         public static void CreateFile(string _path, string _content)
         {
             FileStream file = new FileStream(_path, FileMode.Create, FileAccess.Write);
             StreamWriter writer = new StreamWriter(file);
             writer.WriteLine(_content);
             writer.Close();
             file.Close();
             Console.WriteLine(string.Format("生成{0}", _path));
         }

         /// <summary>
         /// 删除指定文件夹下的子文件(不含子文件夹)
         /// </summary>
         /// <param name="_folderPath">文件夹路径</param>
         public static void ClearFiles(string _folderPath)
         {
             Console.WriteLine("开始删除文件,文件夹目录为" + _folderPath);
             if (!Directory.Exists(_folderPath))
             {
                 Console.WriteLine("指定的文件路径不存在");
                 return;
             }
             var files = Directory.GetFiles(_folderPath);
             foreach (var a in files)
             {
                 File.Delete(a);
             }
             Console.WriteLine("删除完成");
         }

         /// <summary>
         /// 获取当前exe的上层几层路径
         /// </summary>
         /// <param name="_upperNum">向上几级</param>
         /// <returns>路径</returns>
         public static string GetPath(int _upperNum)
         {
             string exePath = Directory.GetCurrentDirectory();
             string[] temp = exePath.Split("\\".ToCharArray());
             string path = string.Empty;
             ; i < temp.Length - _upperNum; i++)
             {
                 path += temp[i];
                 path += "\\";
             }
             return path;
         }
     }
 }

excel转json文件代码

 using System;
 using System.Collections.Generic;
 using SimpleJSON;
 using System.IO;
 using System.Data.OleDb;
 using System.Data;

 namespace ConfigTool
 {
     public class ExcelToJson
     {
         private string sourcePath;
         private string savePath;
         private Dictionary<string, JSONClass> jsonDic = new Dictionary<string, JSONClass>();
         private int fileNum;
         public Dictionary<string, JSONClass> JsonDic
         {
             get
             {
                 return jsonDic;
             }
         }

         public ExcelToJson(string _sourcePath, string _savePath)
         {
             sourcePath = _sourcePath;
             savePath = _savePath;
         }

         public void CreateJsonFiles()
         {
             Tool.ClearFiles(savePath);
             AllConvertToJsons();
             foreach (var a in jsonDic)
             {
                 string path = string.Format("{0}\\{1}.json", savePath, a.Key);
                 Tool.CreateFile(path, a.Value.ToString());
             }
         }

         public int GetFileCount()
         {
             return fileNum;
         }

         private void AllConvertToJsons()
         {
             jsonDic.Clear();
             var excelPathList = GetAllExcel();
             fileNum = excelPathList.Count;
             foreach (var a in excelPathList)
             {
                 ConvertToJson(a);
             }
         }

         private void ConvertToJson(string _excelPath)
         {
             OleDbConnection connection = CreateExcelOleDbConnection(_excelPath);
             if (connection == null)
             {
                 Console.WriteLine("无法成功生成OleDbConnection");
                 return;
             }
             List<OleDbDataReader> readers = InitExcel(_excelPath, connection);
             ReadersToJson(readers, connection);
         }

         #region ConvertToJson 具体实现方法
         private List<OleDbDataReader> InitExcel(string _excelPath, OleDbConnection _connection)
         {
             if (_connection == null)
             {
                 return null;
             }
             _connection.Open();
             DataTable dataTable = _connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

             List<OleDbDataReader> readers = new List<OleDbDataReader>();
             ; i < dataTable.Rows.Count; i++)
             {
                 string sheetName = dataTable.Rows[i]["Table_Name"].ToString();
                 if (sheetName.Contains("#"))//表中页签开头'#'为注释
                 {
                     continue;
                 }
                 OleDbCommand command = new OleDbCommand(string.Format("select * from [{0}]", sheetName), _connection);
                 readers.Add(command.ExecuteReader());
             }
             return readers;
         }

         private OleDbConnection CreateExcelOleDbConnection(string _excelPath)
         {
             if (!File.Exists(_excelPath))
             {
                 Console.WriteLine("未找到指定文件" + _excelPath);
                 return null;
             }

             string strExtension = Path.GetExtension(_excelPath);
             string initStr = string.Empty;
             switch (strExtension)
             {
                 case ".xls":
                     initStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;\"", _excelPath);
                     break;
                 case ".xlsx":
                     initStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1;\"", _excelPath);
                     break;
                 default:
                     Console.WriteLine("目标文件不是excel文件");
                     return null;
                     break;
             }

             return new OleDbConnection(initStr);
         }

         private void ReadersToJson(List<OleDbDataReader> _readers, OleDbConnection _connection)
         {
             ; i < _readers.Count; i++)
             {
                 OleDbDataReader reader = _readers[i];

                 //获取表头
                 reader.Read();
                 ].ToString();
                 if (configTitle == null || configTitle == "")
                 {
                     Console.WriteLine("表头填写不正确");
                 }
                 ;

                 //跳过无用行
                 while (reader.Read())
                 {
                     nextLineIndex++;
                     ].ToString() == "Start")
                     {
                         break;
                     }
                 }

                 //存储json的key,simplejson无法直接获取key
                 int maxRowNum = reader.FieldCount;
                 JSONClass jsonKey = new JSONClass();
                 JSONClass jsonData = new JSONClass();
                 reader.Read();
                 ; j < maxRowNum; j++)
                 {
                     string key = reader[j].ToString();
                     jsonKey.Add(key, key);
                 }
                 jsonData.Add("variate", jsonKey);

                 //依次按行读取有效数据
                 while (reader.Read())
                 {
                     ].ToString();
                     if (key == "End")
                     {
                         break;
                     }

                     JSONClass curLineJson = new JSONClass();
                     ; j < maxRowNum; j++)
                     {
                         curLineJson.Add(jsonKey[j - ], reader[j].ToString());
                     }
                     jsonData.Add(key, curLineJson);
                 }
                 reader.Close();

                 //将当前页签的json文件存储到字典中
                 if (jsonDic.ContainsKey(configTitle))
                 {
                     jsonDic[configTitle].Add(jsonData);
                 }
                 else
                 {
                     jsonDic.Add(configTitle, jsonData);
                 }
             }
             _connection.Close();
         }
         #endregion ConvertToJson 具体实现方法

         /// <summary>
         /// 获取源文件夹中的excel文件,文件名中的"###"作为注释,含有"###"的文件不计进行转换
         /// </summary>
         /// <returns>excel文件路径列表</returns>
         private List<string> GetAllExcel()
         {
             DirectoryInfo dirInfo = new DirectoryInfo(sourcePath);
             FileInfo[] fileInfos = dirInfo.GetFiles();
             List<string> rtnValue = new List<string>();
             foreach (var a in fileInfos)
             {
                 if (a.FullName.Contains("###"))
                 {
                     continue;
                 }
                 if (a.FullName.Contains(".xlsx")
                     || a.FullName.Contains(".xls"))
                 {
                     if (rtnValue.Contains(a.FullName))
                     {
                         continue;
                     }
                     rtnValue.Add(a.FullName);
                 }
             }
             return rtnValue;
         }
     }
 } 

总结:

起始最核心的部分还是读取excel的部分,感觉应该对OleDbDataReader做一下说明:OleDbDataReader是一行一行来读取excel的读完一行再读下一行。我所写的确定表头,确定excel有效数据开始行就是利用这个性质来做的。

ps.刚开始理解不好,写了好几个无用的循环,后来反应过来改掉了(手动捂脸)。

excel转json工具的制作(C#语言)的更多相关文章

  1. Python——Excel转Json工具

    Python工具Excel转Json 前置条件 1.安装python 下载python 我下载的是2.7: 2.配置环境变量 我的电脑右键--属性--高级系统设置--环境变量: 添加python的安装 ...

  2. Excel转Json工具

    应用程序在本地的数据配置的格式一般有JSON.XML.YAML.INI等格式,但是如果直接编写JSON数据往往不是特别方便, 今天给大家分享的是如何在EXCEL配置好数据,然后一键转换成JSON和C# ...

  3. TableML-GUI篇(Excel编译/解析工具)

    项目情况 本文接上篇TableML Excel编译/解析工具,本文主要介绍GUI工具的使用,及配置项,如果你想了解此工具更加详细的说明,请阅读上篇文章. 项目地址:https://github.com ...

  4. Excel转Json,Json转CSharp

    一份给策划最好的礼物!就是:Excel2Json2CSharp 策划配置Excel,动不动就要改数值啊,增加字段啊. 程序这边对应的解析类就得改动啊.整一个麻烦了得! 所以我就整理了这个Excel2J ...

  5. Octopus——excel导入导出工具

    Octopus Octopus是一个简易的Excel导入导出工具.目前主要就两个功能: 导入:将excel中一行数据转换为指定的java对象,并通过指定的正则表达式检查合法性. 导出:按照给定的xml ...

  6. Excel转Json

    参考: Excel2JSON Excel转JSON Excel另存为JSON的技巧  (office的插件) excel2json 游戏程序员的自我修养 (其他人写的工具) Excel转JSON格式- ...

  7. 强大的json工具:fastJson

    fastJson   FastJSON是一个很好的java开源json工具类库,相比其他同类的json类库,它的速度的确是fast,最快!但是文档做得不好,在应用前不得不亲测一些功能.   实际上其他 ...

  8. 使用bison和yacc制作脚本语言(1)

    使用bison和yacc制作脚本语言(1) 环境: 环境 windows 10 Cygwin64 语言 C 工具 mingw bison flex 主要是使用bison和flex这两个软件,编译器无所 ...

  9. java简易excel导入导出工具(封装POI)

    Octopus 如何导入excel 如何导出excel github项目地址 Octopus Octopus 是一个简单的java excel导入导出工具. 如何导入excel 下面是一个excel文 ...

随机推荐

  1. Chrome 开发工具之Sources

    Sources面板主要用于查看web站点的资源列表及javascript代码的debug 熟悉面板 了解完面板之后,下面来试试这些功能都是如何使用的. 文件列表 展示当前页面内所引用资源的列表,和平常 ...

  2. ionic 发布 inoc显示不正确

    前两天因为学习的问题,把本地环境给搞崩了,然后重新安装环境之后发现生成的安装包不能使用,然后找了很多原因都不能解决,因为之前发布ios的时候使用命令 ionic resources的时候就可以将图标显 ...

  3. 面向对象继承 (for in 原型链查找属性)

    window.onload=function(){ new Preson('liujian','男').show(); new Work('liujian','男','工人').show(); new ...

  4. thinkphp访问不存在的模块或者方法跳转到404页面

    使用的thinkphp 版本是3.2.0, 在config.php中配置 404地址,即可: 'TMPL_EXCEPTION_FILE' => './Application/Home/View/ ...

  5. React项目(一):markdown编辑器

    在之前的React官网教程中,提到了用Remarkable为插件的markdown评论框.现在就来正儿八经地用另外一个插件marked.js做一个markdown编辑器吧! 准备工作 或许在做之前,应 ...

  6. mysql ,服务器耗时测试

    测试一 字段:ID,test,number 电脑配置:8g内存 同时写入超过5w条,就会卡死 错误提示 Fatal error: Allowed memory size of bytes exhaus ...

  7. SqlServer批量刷数据执行事务回滚语句备份

    企业进行对数据库执行刷数据工作,一段很长的语句希望同时成功或者失败时用到. 1.建立测试环境 /**************************************************** ...

  8. Sublime Text 3 Emmet插件安装

    一.手动安装:   1. Emmet (ex-Zen Coding) for Sublime Text  http://emmet.io (1) 下载:https://github.com/serge ...

  9. CH模拟赛 拆地毯

    /* MST,注意只能加K条边,但是备选是M条边 */ #include<iostream> #include<cstdio> #include<string> # ...

  10. Android通过Http连接MySQL 实现登陆/注册(数据库+服务器+客户端)

    写在最前: 在实际开发中,相信每个项目都会有用户登陆注册功能,这个实现的方法很多,下面是我实现的方法,供大家交流. 新人发帖,万分紧张,怎么样才能装作一副经常发帖的样子不被别人看出来呢-,- ? 好了 ...