using ExcelDataReader; using FirstVillain.ClassBuild; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.IO; namespace FirstVillain.Converter { [Serializable] public class Wrapper { public List list; } public static class JsonConverter { private static Dictionary _columnIdxDict; private static Dictionary _columnTypeDict; private static Dictionary _typeMap; public static void ExcelToJsonAndClass(string excelPath, string jsonPath, string entityPath) { string[] allFiles = Directory.GetFiles(excelPath); foreach (var excel in allFiles) { if (Path.GetExtension(excel) != ".xlsx") { continue; } using (var stream = File.Open(excel, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var reader = ExcelReaderFactory.CreateReader(stream)) { var excelData = reader.AsDataSet(); for (int i = 0; i < excelData.Tables.Count; i++) { if (excelData.Tables[i].TableName.StartsWith("#")) { continue; } string jsonName = "J" + excelData.Tables[i].TableName; string outPath = Path.Combine(jsonPath, jsonName + ".json"); if (File.Exists(outPath)) { File.Delete(outPath); } var classBuilder = new ClassBuilder(jsonName + "Data"); var jsonBase = new JObject(); var jsonArray = new JArray(); SetCoumnData(excelData.Tables[i].Rows[0], excelData.Tables[i].Rows[1]); int columnCount = _columnIdxDict.Count; for (int j = 2; j < excelData.Tables[i].Rows.Count; j++) { var json = new JObject(); foreach (var nameData in _columnIdxDict) { var data = excelData.Tables[i].Rows[j][nameData.Value]; if (_columnTypeDict[nameData.Value] == typeof(string)) { json.Add(nameData.Key, data.ToString()); } else if (_columnTypeDict[nameData.Value] == typeof(int)) { if (int.TryParse(data.ToString(), out int result)) { json.Add(nameData.Key, result); } } else if (_columnTypeDict[nameData.Value] == typeof(float)) { if (float.TryParse(data.ToString(), out float result)) { json.Add(nameData.Key, result); } } else { throw new Exception("Not supporting type of column"); } } jsonArray.Add(json); } jsonBase.Add("list", jsonArray); File.WriteAllText(outPath, jsonBase.ToString()); classBuilder.CreateCode(_typeMap, entityPath); } } } } } private static void SetCoumnData(DataRow nameRow, DataRow typeRow) { _columnIdxDict = new Dictionary(); _columnTypeDict = new Dictionary(); _typeMap = new Dictionary(); for (int i = 0; i < nameRow.Table.Columns.Count; i++) { if (nameRow[i].ToString().StartsWith("#")) { continue; } _columnIdxDict.Add(nameRow[i].ToString(), i); _columnTypeDict.Add(i, ConvertType(typeRow[i].ToString())); _typeMap.Add(nameRow[i].ToString(), ConvertType(typeRow[i].ToString())); } } private static Type ConvertType(string typeString) { switch (typeString) { default: return typeof(string); case "int": return typeof(int); case "float": return typeof(float); } } public static List GetDataList(string json) { var data = JsonConvert.DeserializeObject>(json); return data.list; } } }