private static void ToTxtAsset(string excelPath, string outputPath) { try { var book = EEWorkbook.Load(excelPath); if (book == null) { return; } foreach (var sheet in book.sheets) { if (sheet == null) { continue; } if (!IsValidSheet(sheet)) { continue; } //var sheetData = ToSheetData(sheet); var sheetData = ToSheetDataRemoveEmptyColumn(sheet); ToTxtAsset(excelPath, sheet.name, outputPath, sheetData); } } catch (Exception e) { EELog.LogError(e.ToString()); AssetDatabase.Refresh(); } }
private static Dictionary <string, string> ToCSharpArray(string excelPath) { var lst = new Dictionary <string, string>(); var book = EEWorkbook.Load(excelPath); if (book == null) { return(lst); } foreach (var sheet in book.sheets) { if (sheet == null) { continue; } if (!IsValidSheet(sheet)) { EELog.Log(string.Format("Skipped sheet {0} in file {1}.", sheet.name, excelPath)); continue; } var sheetData = ToSheetData(sheet); var csTxt = ToCSharp(sheetData, sheet.name); lst.Add(sheet.name, csTxt); } return(lst); }
private void ParseOneDataTable(Type dataTableType) { try { //var dataTableClassName = dataTableType.Name; var headName = GetDataTableHead(dataTableType); //dataTableClassName.Substring(0, dataTableClassName.IndexOf(EESettings.Current.DataTableClassNamePostfix, StringComparison.Ordinal)); var filePath = EESettings.Current.GeneratedAssetPath.Substring(EESettings.Current.GeneratedAssetPath.IndexOf("Resources/", StringComparison.Ordinal) + "Resources/".Length) + headName; var table = Resources.Load(filePath) as RowDataCollection; if (table == null) { EELog.LogError("EEDataManager: Load asset error with " + filePath); return; } var dataDict = new RowDataDictionary(); for (var i = 0; i < table.GetDataCount(); ++i) { var data = table.GetData(i); dataDict.Add(data.ID, data); } var rowDataType = GetRowDataClassType(dataTableType); tableDataDic.Add(rowDataType, dataDict); } catch (Exception e) { EELog.LogError(e.ToString()); } }
public static void OpenWithFile(string filePath) { try { if (string.IsNullOrEmpty(filePath)) { return; } var fullPath = filePath; if (!Path.IsPathRooted(filePath)) { if (filePath.StartsWith("Assets/")) { filePath = filePath.Substring("Assets/".Length); } fullPath = Path.Combine(Application.dataPath, filePath); } if (!File.Exists(fullPath)) { return; } var workbook = EEWorkbook.Load(fullPath); var window = GetWindow <EEWorkbookEditor>(WindowName); window.Show(); window.SetWorkbook(workbook); } catch (Exception e) { EELog.LogError(e.ToString()); } }
private static string ToCSharpInspector(string sheetName, string fileName) { try { var inspectorClassName = EESettings.Current.GetSheetInspectorClassName(fileName, sheetName); var csFile = new StringBuilder(1024); csFile.Append("//------------------------------------------------------------------------------\n"); csFile.Append("// <auto-generated>\n"); csFile.Append("// This code was generated by EasyExcel.\n"); csFile.Append("// Runtime Version: " + EEConstant.Version + "\n"); csFile.Append("//\n"); csFile.Append("// Changes to this file may cause incorrect behavior and will be lost if\n"); csFile.Append("// the code is regenerated.\n"); csFile.Append("// </auto-generated>\n"); csFile.Append("//------------------------------------------------------------------------------"); csFile.Append("\nusing UnityEditor;\nusing EasyExcel;\n\n"); csFile.Append(string.Format("namespace {0}\n", EESettings.Current.GetNameSpace(fileName))); csFile.Append("{\n"); csFile.Append(string.Format("\t[CustomEditor(typeof({0}))]\n", EESettings.Current.GetSheetClassName(fileName, sheetName) /*sheetName, EESettings.Current.SheetDataPostfix*/)); csFile.Append("\tpublic class " + inspectorClassName + " : EEAssetInspector\n"); csFile.Append("\t{\n"); csFile.Append("\t}\n"); csFile.Append("}\n"); return(csFile.ToString()); } catch (Exception ex) { EELog.LogError(ex.ToString()); } return(""); }
private static Dictionary <string, string> ToGolangArray(string excelPath) { var lst = new Dictionary <string, string>(); var book = EEWorkbook.Load(excelPath); if (book == null) { return(lst); } string fileName = Path.GetFileName(excelPath); foreach (var sheet in book.sheets) { if (sheet == null) { continue; } if (!IsValidSheet(sheet)) { EELog.Log(string.Format("Skipped sheet [{0}] in file <{1}>.", sheet.name, fileName)); continue; } var sheetData = ToSheetData(sheet); var csTxt = ToGolang(sheetData, sheet.name, fileName); lst.Add(sheet.name, csTxt); } return(lst); }
public static void GenerateScriptableObjects(string xlsxPath, string assetPath) { try { xlsxPath = xlsxPath.Replace("\\", "/"); assetPath = assetPath.Replace("\\", "/"); if (!Directory.Exists(xlsxPath)) { EditorUtility.DisplayDialog("EasyExcel", "Xls/xlsx path doesn't exist.", "OK"); return; } xlsxPath = xlsxPath.Replace("\\", "/"); assetPath = assetPath.Replace("\\", "/"); if (!assetPath.EndsWith("/")) { assetPath += "/"; } if (Directory.Exists(assetPath)) { Directory.Delete(assetPath, true); } Directory.CreateDirectory(assetPath); AssetDatabase.Refresh(); var filePaths = Directory.GetFiles(xlsxPath); var count = 0; for (var i = 0; i < filePaths.Length; ++i) { var filePath = filePaths[i].Replace("\\", "/"); if (!IsExcelFile(filePath)) { continue; } UpdateProgressBar(i, filePaths.Length, ""); ToScriptableObject(filePath, assetPath); count++; } EELog.Log("Assets are generated successfully."); ClearProgressBar(); AssetDatabase.Refresh(); EELog.Log(string.Format("Import done. {0} sheets were imported.", count)); } catch (Exception e) { EELog.LogError(e.ToString()); ClearProgressBar(); AssetDatabase.Refresh(); } }
public void Dump() { try { foreach (var t in sheets) { t.Dump(); } } catch (Exception e) { EELog.LogError(e.ToString()); } }
private EEWorkbook(ExcelWorkbook workbook) { try { foreach (var sheet in workbook.Worksheets) { sheets.Add(new EEWorksheet(sheet)); } } catch (Exception e) { EELog.LogError(e.ToString()); } }
private static void OnScriptsReloaded() { if (!EditorPrefs.GetBool(EEConverter.csChangedKey, false)) { return; } EditorPrefs.SetBool(EEConverter.csChangedKey, false); var historyExcelPath = EditorPrefs.GetString(EEConverter.excelPathKey); if (string.IsNullOrEmpty(historyExcelPath)) { return; } EELog.Log("Scripts are reloaded, start generating assets..."); EEConverter.GenerateScriptableObjects(historyExcelPath, Environment.CurrentDirectory + "/" + EESettings.Current.GeneratedAssetPath); }
private static void OpenAboutWindow() { try { if (EditorApplication.isCompiling) { EELog.Log("Waiting for Compiling completed."); return; } var window = GetWindowWithRect <EEAboutWindow>(new Rect(0, 0, 480, 320), true, "About EasyExcel", true); window.Show(); } catch (Exception e) { EELog.LogError(e.ToString()); } }
//[MenuItem("Tools/EasyExcel/Workbook Editor", false, 9)] private static void MenuOpenWindow() { try { if (EditorApplication.isCompiling) { EELog.Log("Waiting for Compiling completed."); return; } var window = GetWindow <EEWorkbookEditor>(WindowName); window.Show(); } catch (Exception e) { EELog.LogError(e.ToString()); } }
public static EEWorkbook Create(string firstSheetName = "Sheet 1") { try { using (var ep = new ExcelPackage()) { ep.Workbook.Worksheets.Add(firstSheetName); var workbook = new EEWorkbook(ep.Workbook); return(workbook); } } catch (Exception e) { EELog.LogError(e.ToString()); return(null); } }
public static void OpenSettingsWindow() { try { if (EditorApplication.isCompiling) { EELog.Log("Waiting for Compiling completed."); return; } var window = GetWindowWithRect <EESettingsEditor>(new Rect(0, 0, 480, 640), true, "Settings", true); window.Show(); } catch (Exception e) { EELog.LogError(e.ToString()); } }
public static EEWorkbook Load(string path) { try { var file = new FileInfo(path); using (var ep = new ExcelPackage(file)) { var workbook = new EEWorkbook(ep.Workbook); return(workbook); } } catch (Exception e) { EELog.LogError(e.ToString()); } return(null); }
private void OnGUI() { EEGUIStyle.Ensure(); try { if (_currentEeWorkbook != null) { EditorDrawHelper.DrawTableTab(_currentEeWorkbook, ref selectIndex); _currentEeWorksheet = _currentEeWorkbook.sheets[selectIndex]; EditorDrawHelper.DrawTable(_currentEeWorksheet); DrawMenus(); } } catch (Exception e) { EELog.LogError(e.ToString()); } }
private static bool OnOpenExcelFile(int instanceId, int line) { try { var asset = EditorUtility.InstanceIDToObject(instanceId) as EESettings; if (asset == null) { return(false); } EESettingsEditor.OpenSettingsWindow(); return(true); } catch (Exception e) { EELog.LogError(e.ToString()); } return(false); }
/*public void SetCellTypeByRow(int row, CellType type) * { * for (var column = 0; column < columnCount; column++) * { * var cell = GetCell(row, column); * if (cell != null) cell.type = type; * } * } * * public void SetCellTypeByColumn(int column, CellType type, List<string> values = null) * { * for (var row = 1; row <= rowCount; row++) * { * var cell = GetCell(row, column); * if (cell == null) continue; * cell.type = type; * if (values != null) cell.ValueSelected = values; * } * }*/ public void Dump() { try { var msg = ""; for (var row = 0; row < RowCount; row++) { for (var column = 0; column < ColumnCount; column++) { msg += string.Format("{0} ", GetCellValue(row, column)); } msg += "\n"; } Debug.Log(msg); } catch (Exception e) { EELog.LogError(e.ToString()); } }
public void SaveToFile(string path) { try { var output = new FileInfo(path); using (var ep = new ExcelPackage()) { foreach (var s in sheets) { var sheet = ep.Workbook.Worksheets.Add(s.name); s.CopyTo(sheet); } ep.SaveAs(output); } } catch (Exception e) { EELog.LogError(e.ToString()); } }
public void Load() { #if UNITY_EDITOR if (!EESettings.Current.GeneratedAssetPath.Contains("/Resources/")) { EditorUtility.DisplayDialog("EasyExcel", string.Format( "AssetPath of EasyExcel Settings MUST be in Resources folder.\nCurrent is {0}.", EESettings.Current.GeneratedAssetPath), "OK"); return; } #endif tableDataDic.Clear(); var baseDataTableType = typeof(RowDataCollection); foreach (var dataTableType in baseDataTableType.Assembly.GetTypes().Where(t => t.IsSubclassOf(baseDataTableType))) { ParseOneDataTable(dataTableType); } EELog.Log(string.Format("{0} tables loaded.", tableDataDic.Count)); }
public static void GenerateCSharpFiles(string excelPath, string csPath) { try { excelPath = excelPath.Replace("\\", "/"); csPath = csPath.Replace("\\", "/"); if (!Directory.Exists(excelPath)) { EditorUtility.DisplayDialog("EasyExcel", "Excel files path doesn't exist.", "OK"); return; } if (!Directory.Exists(csPath)) { var opt = EditorUtility.DisplayDialogComplex("EasyExcel", string.Format( "EasyExcelSettings CSharpPath doesn't exist. Would you like to create it?\n{0}", csPath), "Create", "Cancel", "Quit"); switch (opt) { case 0: Directory.CreateDirectory(csPath); break; case 1: case 2: return; } } var tmpPath = Environment.CurrentDirectory + "/EasyExcelTmp/"; if (Directory.Exists(tmpPath)) { Directory.Delete(tmpPath, true); } Directory.CreateDirectory(tmpPath); excelPath = excelPath.Replace("\\", "/"); csPath = csPath.Replace("\\", "/"); if (!csPath.EndsWith("/")) { csPath += "/"; } var csChanged = false; var filePaths = Directory.GetFiles(excelPath); for (var i = 0; i < filePaths.Length; ++i) { var excelFilePath = filePaths[i].Replace("\\", "/"); if (i + 1 < filePaths.Length) { UpdateProgressBar(i + 1, filePaths.Length, ""); } else { ClearProgressBar(); } if (!IsExcelFile(excelFilePath)) { continue; } var newCsDict = ToCSharpArray(excelFilePath); foreach (var newCs in newCsDict) { var cSharpFileName = EESettings.Current.GetCSharpFileName(newCs.Key); var tmpCsFilePath = tmpPath + cSharpFileName; var csFilePath = csPath + cSharpFileName; var shouldWrite = true; if (File.Exists(csFilePath)) { var oldCs = File.ReadAllText(csFilePath); shouldWrite = oldCs != newCs.Value; } if (!shouldWrite) { continue; } csChanged = true; var streamwriter = new StreamWriter(tmpCsFilePath, false); streamwriter.Write(newCs.Value); streamwriter.Flush(); streamwriter.Close(); } } if (csChanged) { EditorPrefs.SetBool(csChangedKey, true); var files = Directory.GetFiles(tmpPath); foreach (var s in files) { var p = s.Replace("\\", "/"); File.Copy(s, csPath + p.Substring(p.LastIndexOf("/", StringComparison.Ordinal)), true); } Directory.Delete(tmpPath, true); AssetDatabase.Refresh(); EELog.Log("Scripts are generated, wait for generating assets..."); } else { EELog.Log("No CSharp files changed, begin generating assets..."); ClearProgressBar(); var historyExcelPath = EditorPrefs.GetString(excelPathKey); if (!string.IsNullOrEmpty(historyExcelPath)) { GenerateScriptableObjects(historyExcelPath, Environment.CurrentDirectory + "/" + EESettings.Current.GeneratedAssetPath); } } } catch (Exception e) { EELog.LogError(e.ToString()); EditorPrefs.SetBool(csChangedKey, false); ClearProgressBar(); AssetDatabase.Refresh(); } }
public static void GenerateGolangFiles(string excelPath, string goPath) { try { excelPath = excelPath.Replace("\\", "/"); goPath = goPath.Replace("\\", "/"); if (!Directory.Exists(excelPath)) { EditorUtility.DisplayDialog("EasyExcel", "Excel files path doesn't exist.", "OK"); return; } if (!Directory.Exists(goPath)) { Directory.CreateDirectory(goPath); } var tmpPath = Environment.CurrentDirectory + "/EasyExcelTmp/"; if (Directory.Exists(tmpPath)) { Directory.Delete(tmpPath, true); } Directory.CreateDirectory(tmpPath); excelPath = excelPath.Replace("\\", "/"); goPath = goPath.Replace("\\", "/"); if (!goPath.EndsWith("/")) { goPath += "/"; } var goChanged = false; var filePaths = Directory.GetFiles(excelPath); var loadGoFileBuilder = new StringBuilder().AppendLine("package gamedata").AppendLine().AppendLine("func LoadAllTables() {"); for (var i = 0; i < filePaths.Length; ++i) { var excelFilePath = filePaths[i].Replace("\\", "/"); if (i + 1 < filePaths.Length) { UpdateProgressBar(i + 1, filePaths.Length, ""); } else { ClearProgressBar(); } if (!IsExcelFile(excelFilePath)) { continue; } string fileName = Path.GetFileName(excelFilePath); var newGoTxtDic = ToGolangArray(excelFilePath); foreach (var newGoInfo in newGoTxtDic) { var cSharpFileName = EESettings.Current.GetGolangFileName(fileName, newGoInfo.Key); var tmpCsFilePath = tmpPath + cSharpFileName; var csFilePath = goPath + cSharpFileName; loadGoFileBuilder.AppendLine($" Load_{EESettings.Current.GetSheetClassName(fileName, newGoInfo.Key)}_Map()"); var shouldWrite = true; if (File.Exists(csFilePath)) { var oldCs = File.ReadAllText(csFilePath); shouldWrite = oldCs != newGoInfo.Value; } if (!shouldWrite) { continue; } goChanged = true; File.WriteAllText(tmpCsFilePath, newGoInfo.Value, Encoding.UTF8); } } // LoadAllTables.go loadGoFileBuilder.AppendLine("}"); var loadGoFileBuilderStr = loadGoFileBuilder.ToString(); var tempLoadAllTablesFilePath = tmpPath + "LoadAllTables.go"; var targetLoadAllTablesFilePath = goPath + "LoadAllTables.go"; if (File.Exists(targetLoadAllTablesFilePath)) { var oldCs = File.ReadAllText(targetLoadAllTablesFilePath); goChanged = goChanged || oldCs != loadGoFileBuilderStr; } else { goChanged = true; } File.WriteAllText(tempLoadAllTablesFilePath, loadGoFileBuilderStr, Encoding.UTF8); // if (goChanged) { EditorPrefs.SetBool(csChangedKey, true); var files = Directory.GetFiles(tmpPath); foreach (var s in files) { var p = s.Replace("\\", "/"); File.Copy(s, goPath + p.Substring(p.LastIndexOf("/", StringComparison.Ordinal)), true); } Directory.Delete(tmpPath, true); EELog.Log("Scripts are generated, wait for generating assets..."); } else { EELog.Log("No GoLang files changed, begin generating assets..."); ClearProgressBar(); var historyExcelPath = EditorPrefs.GetString(excelPathKey); if (!string.IsNullOrEmpty(historyExcelPath)) { // 生成go资源 if (!string.IsNullOrWhiteSpace(EESettings.Current.GeneratedGoAssetPath)) { GenerateGoAssets(historyExcelPath, Environment.CurrentDirectory + "/" + EESettings.Current.GeneratedGoAssetPath); } } } } catch (Exception e) { EELog.LogError(e.ToString()); EditorPrefs.SetBool(csChangedKey, false); ClearProgressBar(); AssetDatabase.Refresh(); } }
private static string ToGolang(SheetData sheetData, string sheetName, string fileName) { string _keyFieldNames2String(List <string> keys) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < keys.Count; i++) { var key = keys[i]; key = key.Substring(0, 1).ToUpper() + key.Substring(1); builder.Append("\"").Append(key).Append("\","); } if (keys.Count > 0) { builder.Remove(builder.Length - 1, 1); } return(builder.ToString()); } string _createGoMap(List <string> keyTypes, string valueStr) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < keyTypes.Count; i++) { var keyType = keyTypes[i]; builder.Append("map[").Append(keyType).Append("]"); } return(builder.Append(valueStr).ToString()); } string _fillGoMap(List <string> keyTypes, string _sheetName, string valueStr) { // {sheetName}_Map{fillGoMap(keyFieldTypes, sheetName)} = &record var mapName = $" {_sheetName}_Map"; StringBuilder builder = new StringBuilder(); for (int i = 0; i < keyTypes.Count; i++) { var keyType = keyTypes[i]; mapName += $"[keys[{i}].({keyType})]"; builder.Append(mapName).Append(" = "); for (int j = i + 1; j < keyTypes.Count; j++) { var keyType2 = keyTypes[j]; builder.Append($"map[{keyType}]"); } if (i == keyTypes.Count - 1) { // 最后一个,直接赋值 builder.AppendLine("&record"); } else { // 不是最后一个的话,则新建 builder.AppendLine(valueStr); } } return(builder.ToString()); } try { var rowDataClassName = EESettings.Current.GetRowDataClassName(fileName, sheetName); var sheetClassName = EESettings.Current.GetSheetClassName(fileName, sheetName); var csFile = new StringBuilder(2048); csFile.Append("//------------------------------------------------------------------------------\n"); csFile.Append("// <auto-generated>\n"); csFile.Append("// This code was generated by EasyExcel.\n"); csFile.Append("// Runtime Version: " + EEConstant.Version + "\n"); csFile.Append("//\n"); csFile.Append("// Changes to this file may cause incorrect behavior and will be lost if\n"); csFile.Append("// the code is regenerated.\n"); csFile.Append("// </auto-generated>\n"); csFile.Append("//------------------------------------------------------------------------------"); csFile.Append("\npackage gamedata\n"); // csFile.Append("\nimport \"github.com/fuliufuliu/leaf/recordfile\"\n"); csFile.Append("\nimport \"reflect\"\n"); csFile.Append("type " + sheetClassName + " struct {\n"); var columnCount = sheetData.ColumnCount; // Get field names var fieldsName = new string[columnCount]; var fieldsDis = new string[columnCount]; for (var col = 0; col < columnCount; col++) { fieldsDis[col] = sheetData.Get(EESettings.Current.DiscriptionRowIndex, col); fieldsName[col] = sheetData.Get(EESettings.Current.NameRowIndex, col); } // Get field types and Key column var fieldsLength = new string[columnCount]; var fieldsType = new string[columnCount]; List <string> keyFieldNamesFull = new List <string>(); List <string> keyFieldNames = new List <string>(); List <string> keyFieldTypes = new List <string>(); for (var col = 0; col < columnCount; col++) { var cellInfo = sheetData.Get(EESettings.Current.TypeRowIndex, col); fieldsLength[col] = null; fieldsType[col] = cellInfo; if (cellInfo.EndsWith("]")) { var startIndex = cellInfo.IndexOf('['); fieldsLength[col] = cellInfo.Substring(startIndex + 1, cellInfo.Length - startIndex - 2); fieldsType[col] = cellInfo.Substring(0, startIndex); } var varName = fieldsName[col]; var varLen = fieldsLength[col]; var varType = fieldsType[col]; if (varName.EndsWith(":Key") || varName.EndsWith(":key") || varName.EndsWith(":KEY")) { var splits = varName.Split(':'); if ((varType.Equals("int") || varType.Equals("string")) && varLen == null) { keyFieldNamesFull.Add(varName); fieldsName[col] = splits[0]; keyFieldNames.Add(fieldsName[col]); keyFieldTypes.Add(GetGoType(varType)); } } } if (keyFieldNamesFull.Count == 0) { EELog.LogError("Cannot find Key column in sheet " + sheetName); } // type Config_Card_Sheet struct { // CardId int // 卡牌id; // CardClass int // 卡牌品类; // CardName string // 卡牌名称; // AppearanceLevel int // 出场等级; // Skill1Id int // 技能1_ID; // } List <string> keyTypes = new List <string>(4); for (var col = 0; col < columnCount; col++) { var varName = fieldsName[col]; // 大写的字段是公有的,小写字段表示私有 if (!string.IsNullOrWhiteSpace(varName) && varName.Length > 1) { varName = varName.Substring(0, 1).ToUpper() + varName.Substring(1); } var varLen = fieldsLength[col]; var varType = GetGoType(fieldsType[col]); bool isKeyField = keyFieldNamesFull.Count > 0 && keyFieldNames.Contains(varName); if (IsSupportedColumnType(varType)) { if (isKeyField) { keyTypes.Add(varType); } if (varLen == null) { csFile.AppendFormat("\t{0} {1} // {2};\n", varName, varType, fieldsDis[col].Replace("\n", " ")); } else { csFile.AppendFormat("\t{0} []{1} // {2};\n", varName, varType, fieldsDis[col].Replace("\n", " ")); } } } csFile.Append("}\n\n"); // 是key的字段列表 csFile.Append($"\nvar {sheetClassName}_Keys = []string{{{_keyFieldNames2String(keyFieldNames)}}}\n\n"); // var Config_Card_Map = map[int]*Config_Card_Sheet{} csFile.Append($"\nvar {sheetClassName}_Map = {_createGoMap(keyFieldTypes, "*" + sheetClassName + "{}")}\n\n"); // func Load_Config_Card_Map() { // var sheet = readRf(Config_Card_Sheet{}) // for i := 0; i < sheet.NumRecord(); i++ { // record := *sheet.Record(i).(*Config_Card_Sheet) // var keys = make([]interface{}, len(Config_Card_Sheet_Keys)) // for j := 0; j < len(Config_Card_Sheet_Keys); j++ { // valueOfKey := reflect.ValueOf(record).FieldByName(Config_Card_Sheet_Keys[j]).Interface().(int) // keys[0] = valueOfKey // } // Config_Card_Map[keys[0].(int)] = &record // } // } csFile.Append($"\nfunc Load_{sheetClassName}_Map() {{" + $"\n var sheet = readRf({sheetClassName}{{}})"+ $"\n for i := 0; i < sheet.NumRecord(); i++ {{"+ $"\n record := *sheet.Record(i).(*{sheetClassName})"+ $"\n var keys = make([]interface{{}}, len({sheetClassName}_Keys))"+ $"\n for j := 0; j < len({sheetClassName}_Keys); j++ {{"+ $"\n valueOfKey := reflect.ValueOf(record).FieldByName({sheetClassName}_Keys[j]).Interface().(int)"+ $"\n keys[j] = valueOfKey"+ $"\n }}"+ $"\n{_fillGoMap(keyFieldTypes, sheetClassName, "*" + sheetClassName + "{}")}" + $"\n }}"+ $"\n}}\n\n"); return(csFile.ToString()); } catch (Exception ex) { EELog.LogError(ex.ToString()); } return(""); }
private static string ToCSharp(SheetData sheetData, string sheetName, string fileName) { try { var rowDataClassName = EESettings.Current.GetRowDataClassName(fileName, sheetName); var sheetClassName = EESettings.Current.GetSheetClassName(fileName, sheetName); var csFile = new StringBuilder(2048); csFile.Append("//------------------------------------------------------------------------------\n"); csFile.Append("// <auto-generated>\n"); csFile.Append("// This code was generated by EasyExcel.\n"); csFile.Append("// Runtime Version: " + EEConstant.Version + "\n"); csFile.Append("//\n"); csFile.Append("// Changes to this file may cause incorrect behavior and will be lost if\n"); csFile.Append("// the code is regenerated.\n"); csFile.Append("// </auto-generated>\n"); csFile.Append("//------------------------------------------------------------------------------"); csFile.Append("\nusing System;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing EasyExcel;\n\n"); csFile.Append(string.Format("namespace {0}\n", EESettings.Current.GetNameSpace(fileName))); csFile.Append("{\n"); csFile.Append("\t[Serializable]\n"); csFile.Append("\tpublic partial class " + rowDataClassName + " : EERowData\n"); csFile.Append("\t{\n"); // csFile.Append("\t\t[EEKeyField]\n"); csFile.Append("\t\t[SerializeField]\n"); csFile.Append("\t\tpublic string tempId;\n"); csFile.Append("\n"); /*var columnCount = 0; * for (var col = 0; col < sheetData.ColumnCount; col++) * { * if (string.IsNullOrEmpty(sheetData.Get(EESettings.Current.NameRowIndex, col))) * continue; * columnCount++; * }*/ var columnCount = sheetData.ColumnCount; // Get field names var fieldsName = new string[columnCount]; var fieldsDis = new string[columnCount]; for (var col = 0; col < columnCount; col++) { fieldsDis[col] = sheetData.Get(EESettings.Current.DiscriptionRowIndex, col); fieldsName[col] = sheetData.Get(EESettings.Current.NameRowIndex, col); } // Get field types and Key column var fieldsLength = new string[columnCount]; var fieldsType = new string[columnCount]; List <string> keyFieldNamesFull = new List <string>(); List <string> keyFieldNames = new List <string>(); for (var col = 0; col < columnCount; col++) { var cellInfo = sheetData.Get(EESettings.Current.TypeRowIndex, col); fieldsLength[col] = null; fieldsType[col] = cellInfo; if (cellInfo.EndsWith("]")) { var startIndex = cellInfo.IndexOf('['); fieldsLength[col] = cellInfo.Substring(startIndex + 1, cellInfo.Length - startIndex - 2); fieldsType[col] = cellInfo.Substring(0, startIndex); } var varName = fieldsName[col]; var varLen = fieldsLength[col]; var varType = fieldsType[col]; if (varName.EndsWith(":Key") || varName.EndsWith(":key") || varName.EndsWith(":KEY")) { var splits = varName.Split(':'); if ((varType.Equals("int") || varType.Equals("string")) && varLen == null) { keyFieldNamesFull.Add(varName); fieldsName[col] = splits[0]; keyFieldNames.Add(fieldsName[col]); } } } if (keyFieldNamesFull.Count == 0) { EELog.LogError("Cannot find Key column in sheet " + sheetName); } for (var col = 0; col < columnCount; col++) { var varName = fieldsName[col]; var varLen = fieldsLength[col]; var varType = fieldsType[col]; bool isKeyField = keyFieldNamesFull.Count > 0 && keyFieldNames.Contains(varName); if (IsSupportedColumnType(varType)) { if (isKeyField) { csFile.Append("\t\t[EEKeyField]\n"); } csFile.Append("\t\t[SerializeField]\n"); if (varLen == null) { csFile.AppendFormat("\t\tprivate {0} _{1};\n", varType, varName); csFile.Append("\t\t/// <summary>\n"); csFile.AppendFormat("\t\t/// {0}\n", fieldsDis[col].Replace("\n", " ")); csFile.Append("\t\t/// </summary>\n"); csFile.AppendFormat("\t\tpublic {0} {1} {{ get {{ return _{1}; }} }}\n\n", varType, varName); } else { csFile.AppendFormat("\t\tprivate {0}[] _{1};\n", varType, varName); csFile.Append("\t\t/// <summary>\n"); csFile.AppendFormat("\t\t/// {0}\n", fieldsDis[col].Replace("\n", " ")); csFile.Append("\t\t/// </summary>\n"); csFile.AppendFormat("\t\tpublic {0}[] {1} {{ get {{ return _{1}; }} }}\n\n", varType, varName); } } } csFile.AppendFormat("\n\t\tpublic {0}()" + "\n", rowDataClassName); csFile.Append("\t\t{" + "\n"); csFile.Append("\t\t}\n"); csFile.Append("\n#if UNITY_EDITOR\n"); csFile.AppendFormat("\t\tpublic {0}(List<List<string>> sheet, int row, int column)" + "\n", rowDataClassName); csFile.Append("\t\t{" + "\n"); //csFile.Append("\t\t\tcolumn = base._init(sheet, row, column);\n"); for (var col = 0; col < columnCount; col++) { var varType = fieldsType[col]; var varLen = fieldsLength[col]; var varName = fieldsName[col]; if (keyFieldNamesFull.Count > 0 && keyFieldNamesFull.Contains(varName)) { varName = keyFieldNames[keyFieldNamesFull.IndexOf(varName)]; } varName = "_" + varName; if (varType.Equals("int") || varType.Equals("float") || varType.Equals("double") || varType.Equals("long") || varType.Equals("bool")) { if (varLen == null) { csFile.Append("\t\t\t" + varType + ".TryParse(sheet[row][column++], out " + varName + ");\n"); } else { csFile.Append("\t\t\tstring[] " + varName + "Array = sheet[row][column++].Split(\',\');" + "\n"); csFile.Append("\t\t\tint " + varName + "Count = " + varName + "Array.Length;" + "\n"); csFile.Append("\t\t\t" + varName + " = new " + varType + "[" + varName + "Count];\n"); csFile.Append("\t\t\tfor(int i = 0; i < " + varName + "Count; i++)\n"); csFile.Append("\t\t\t\t" + varType + ".TryParse(" + varName + "Array[i], out " + varName + "[i]);\n"); } } else if (varType.Equals("string")) { if (varLen == null) { csFile.Append("\t\t\t" + varName + " = sheet[row][column++] ?? \"" + /*varDefault + */ "\";\n"); } else { csFile.Append("\t\t\tstring[] " + varName + "Array = sheet[row][column++].Split(\',\');" + "\n"); csFile.Append("\t\t\tint " + varName + "Count = " + varName + "Array.Length;" + "\n"); csFile.Append("\t\t\t" + varName + " = new " + varType + "[" + varName + "Count];\n"); csFile.Append("\t\t\tfor(int i = 0; i < " + varName + "Count; i++)\n"); csFile.Append("\t\t\t\t" + varName + "[i] = " + varName + "Array[i];\n"); } } } //csFile.Append("\t\t\treturn column;\n"); csFile.Append("\t\t}\n#endif\n"); csFile.Append("\t}\n\n"); // EERowDataCollection class csFile.Append("\tpublic partial class " + sheetClassName + " : EERowDataCollection\n"); csFile.Append("\t{\n"); csFile.AppendFormat("\t\t[SerializeField]\n\t\tprivate List<{0}> elements = new List<{0}>();\n\n", rowDataClassName); csFile.AppendFormat("\t\tpublic override void AddData(EERowData data)\n\t\t{{\n\t\t\telements.Add(data as {0});\n\t\t}}\n\n", rowDataClassName); csFile.Append("\t\tpublic override int GetDataCount()\n\t\t{\n\t\t\treturn elements.Count;\n\t\t}\n\n"); csFile.Append("\t\tpublic override EERowData GetData(int index)\n\t\t{\n\t\t\treturn elements[index];\n\t\t}\n"); csFile.Append("\t}\n"); csFile.Append("}\n"); return(csFile.ToString()); } catch (Exception ex) { EELog.LogError(ex.ToString()); } return(""); }
private static void ToScriptableObject(string excelPath, string sheetName, string outputPath, SheetData sheetData) { try { string fileName = Path.GetFileName(excelPath); var sheetClassName = EESettings.Current.GetSheetClassName(fileName, sheetName); var asset = ScriptableObject.CreateInstance(sheetClassName); var dataCollect = asset as EERowDataCollection; if (dataCollect == null) { return; } dataCollect.ExcelFileName = fileName; dataCollect.ExcelSheetName = sheetName; var className = EESettings.Current.GetRowDataClassName(fileName, sheetName, true); var dataType = Type.GetType(className); if (dataType == null) { var asmb = Assembly.LoadFrom(Environment.CurrentDirectory + "/Library/ScriptAssemblies/Assembly-CSharp.dll"); dataType = asmb.GetType(className); } if (dataType == null) { EELog.LogError(className + " not exist !"); return; } //var dataCtor = dataType.GetConstructor(Type.EmptyTypes); var dataCtor = dataType.GetConstructor(new [] { typeof(List <List <string> >), typeof(int), typeof(int) }); if (dataCtor == null) { return; } var keySet = new HashSet <object>(); for (var row = EESettings.Current.DataStartIndex; row < sheetData.RowCount; ++row) { // 替换掉单元格中的'\n'为 "\\n" for (var col = 0; col < sheetData.ColumnCount; ++col) { sheetData.Set(row, col, sheetData.Get(row, col).Replace("\n", "\\n")); } // 利用反射构造函数处理数据 var inst = dataCtor.Invoke(new object[] { sheetData.Table, row, 0 }) as EERowData; if (inst == null) { continue; } var keys = inst.GetKeyFieldValues(); var isMultiKey = keys.Count > 1; if (keys.Count == 0) { EELog.LogError("The value of key is null in sheet " + sheetName); continue; } if (!isMultiKey) { var key = keys[0]; if (key is int i && i == 0) { continue; } if (key is string s && string.IsNullOrEmpty(s)) { continue; } if (!keySet.Contains(key)) { dataCollect.AddData(inst); keySet.Add(key); } else { EELog.LogError(string.Format("More than one rows have the same Key [{0}] in Sheet {1}", key, sheetName)); } } else { var isKeysOk = true; // 多个key var groupKey = ""; for (int j = 0; j < keys.Count; j++) { var key = keys[j]; if (key is int i && i == 0) { isKeysOk = false; } else if (key is string s && string.IsNullOrEmpty(s)) { isKeysOk = false; }
private static void ToTxtAsset(string excelPath, string sheetName, string outputPath, SheetData sheetData) { try { string fileName = Path.GetFileName(excelPath); var itemPath = outputPath + EESettings.Current.GetAssetFileName(fileName, sheetName, ".txt"); itemPath = itemPath.Substring(itemPath.IndexOf("Assets", StringComparison.Ordinal)); var keyIndexes = new List <int>(); var validIndexes = new List <int>(); StringBuilder content = new StringBuilder(); StringBuilder titleStr = new StringBuilder(); for (var col = 0; col < sheetData.ColumnCount; ++col) { var cell = sheetData.Get(EESettings.Current.NameRowIndex, col); if (!string.IsNullOrWhiteSpace(cell) && cell.Length > 1) { cell = cell.Substring(0, 1).ToUpper() + cell.Substring(1); validIndexes.Add(col); } if (cell.ToLower().Contains("key")) { keyIndexes.Add(col); var splits = cell.Split(':'); cell = splits[0]; } var varType = GetGoType(cell); titleStr.Append(varType).Append(EESettings.Current.GoTxtFieldSplitStr); } content.Append(titleStr.Remove(titleStr.Length - EESettings.Current.GoTxtFieldSplitStr.Length, EESettings.Current.GoTxtFieldSplitStr.Length) .Append(EESettings.Current.GoTxtRowSplitStr)); StringBuilder newRowStr = new StringBuilder(); var isKeyInvalid = false; for (var row = EESettings.Current.DataStartIndex; row < sheetData.RowCount; ++row) { newRowStr.Clear(); isKeyInvalid = false; for (var col = 0; col < sheetData.ColumnCount; ++col) { if (!validIndexes.Contains(col)) { continue; } var cell = sheetData.Get(row, col); if (keyIndexes.Contains(col) && string.IsNullOrWhiteSpace(cell)) { isKeyInvalid = true; break; } newRowStr.Append(cell).Append(EESettings.Current.GoTxtFieldSplitStr); } if (isKeyInvalid) { continue; } content.Append(newRowStr.Remove(newRowStr.Length - EESettings.Current.GoTxtFieldSplitStr.Length, EESettings.Current.GoTxtFieldSplitStr.Length) .Append(EESettings.Current.GoTxtRowSplitStr)); } if (!FileHelper.IsExistFile(itemPath)) { FileHelper.CreateFile(itemPath); } FileHelper.WriteText(itemPath, content.ToString()); } catch (Exception ex) { EELog.LogError(ex.ToString()); } }
private void ParseOneDataCollection(Type dataCollectionType) { try { var sheetClassName = dataCollectionType.Name; //GetSheetName(dataCollectionType); var collection = dataLoader.Load(sheetClassName); if (collection == null) { EELog.LogError("EEDataManager: Load asset error, sheet name " + sheetClassName); return; } var rowDataType = GetRowDataClassType(collection.ExcelFileName, dataCollectionType); var keyFields = EEUtility.GetRowDataKeyFields(rowDataType); if (keyFields.Count == 0) { EELog.LogError("EEDataManager: Cannot find Key field in sheet " + sheetClassName); return; } if (keyFields.Count == 1) { var keyField = keyFields[0]; var keyType = keyField.FieldType; if (keyType == typeof(int)) { var dataDict = new RowDataDictInt(); for (var i = 0; i < collection.GetDataCount(); ++i) { var data = collection.GetData(i); int key = (int)keyField.GetValue(data); dataDict.Add(key, data); } dataCollectionDictInt.Add(rowDataType, dataDict); } else if (keyType == typeof(string)) { var dataDict = new RowDataDictStr(); for (var i = 0; i < collection.GetDataCount(); ++i) { var data = collection.GetData(i); string key = (string)keyField.GetValue(data); dataDict.Add(key, data); } dataCollectionDictStr.Add(rowDataType, dataDict); } else { EELog.LogError(string.Format("Load {0} failed. There is no valid Key field in ", dataCollectionType.Name)); } } else if (keyFields.Count == 2) { var dataDict = new RowDataTowKeyDict(); for (var i = 0; i < collection.GetDataCount(); ++i) { var data = collection.GetData(i); var key1 = keyFields[0].GetValue(data); var key2 = keyFields[1].GetValue(data); dataDict.Add(new Keys <object, object>(key1, key2), data); } dataCollectionDictTowKeys.Add(rowDataType, dataDict); } else if (keyFields.Count == 3) { var dataDict = new RowDataThreeKeyDict(); for (var i = 0; i < collection.GetDataCount(); ++i) { var data = collection.GetData(i); var key1 = keyFields[0].GetValue(data); var key2 = keyFields[1].GetValue(data); var key3 = keyFields[2].GetValue(data); dataDict.Add(new Keys <object, object, object>(key1, key2, key3), data); } dataCollectionDictThreeKeys.Add(rowDataType, dataDict); } else if (keyFields.Count > 3) { Debug.LogErrorFormat("EasyExcel 导入功能暂不支持 key超过3个的表!"); } } catch (Exception e) { EELog.LogError(e.ToString()); } }
private static string ToCSharp(SheetData sheetData, string sheetName) { try { var rowDataClassName = EESettings.Current.GetRowDataClassName(sheetName); var dataTableClassName = EESettings.Current.GetDataTableClassName(sheetName); var csFile = new StringBuilder(2048); csFile.Append(@"//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by EasyExcel."); csFile.Append("\n// Runtime Version: " + EEConstant.Version + "\n"); csFile.Append(@"// // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------"); csFile.Append("\nusing System;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing EasyExcel;\n\n"); csFile.Append(string.Format("namespace {0}\n", EESettings.Current.NameSpace)); csFile.Append("{\n"); csFile.Append("\t[Serializable]\n"); csFile.Append("\tpublic class " + rowDataClassName + " : RowData\n"); csFile.Append("\t{\n"); var columnCount = 0; for (var col = 0; col < sheetData.columnCount; col++) { if (string.IsNullOrEmpty(sheetData.Get(EESettings.Current.NameRowIndex, col))) { break; } columnCount++; } // Get variable names var variableName = new string[columnCount]; for (var col = 0; col < columnCount; col++) { variableName[col] = sheetData.Get(EESettings.Current.NameRowIndex, col); } // Get variable types var variableLength = new string[columnCount]; var variableType = new string[columnCount]; // skip column 0 for ID for (var col = 1; col < columnCount; col++) { var cellInfo = sheetData.Get(EESettings.Current.TypeRowIndex, col); variableLength[col] = null; variableType[col] = cellInfo; if (cellInfo.EndsWith("]")) { var startIndex = cellInfo.IndexOf('['); variableLength[col] = cellInfo.Substring(startIndex + 1, cellInfo.Length - startIndex - 2); variableType[col] = cellInfo.Substring(0, startIndex); } var varName = variableName[col]; var varLen = variableLength[col]; var varType = variableType[col]; if (varType.Equals("int") || varType.Equals("float") || varType.Equals("double") || varType.Equals("long") || varType.Equals("string") || varType.Equals("bool") || varType.Equals("JObject")) { if (varLen == null) { csFile.Append("\t\tpublic " + varType + " " + varName + ";\n"); } else { csFile.Append("\t\tpublic " + varType + "[] " + varName + ";\n"); } } } //string[] variableDefaults = new string[columnCount]; csFile.Append("\n#if UNITY_EDITOR\n"); csFile.Append("\t\tpublic override int _init(List<List<string>> sheet, int row, int column)" + "\n"); csFile.Append("\t\t{" + "\n"); csFile.Append("\t\t\tcolumn = base._init(sheet, row, column);\n"); // skip column 0 for ID for (var col = 1; col < columnCount; col++) { var varType = variableType[col]; /*variableDefaults[col] = sheetData.At(EasyExcelSettings.Current.DEFAULT_VALUE_ROW_INDEX, col); * if (varType.Equals("bool")) * { * if (variableDefaults[col].Equals("0")) * variableDefaults[col] = "false"; * else * variableDefaults[col] = "true"; * } * * string varDefault = variableDefaults[col];*/ var varLen = variableLength[col]; var varName = variableName[col]; if (varType.Equals("int") || varType.Equals("float") || varType.Equals("double") || varType.Equals("long") || varType.Equals("bool")) { if (varLen == null) { //csFile += "\t\t" + varName + " = " + varDefault + ";\n"; csFile.Append("\t\t\t" + varType + ".TryParse(sheet[row][column++], out " + varName + ");\n"); } else { csFile.Append("\t\t\tstring[] " + varName + "Array = sheet[row][column++].Split(\',\');" + "\n"); csFile.Append("\t\t\tint " + varName + "Count = " + varName + "Array.Length;" + "\n"); csFile.Append("\t\t\t" + varName + " = new " + varType + "[" + varName + "Count];\n"); csFile.Append("\t\t\tfor(int i = 0; i < " + varName + "Count; i++)\n"); csFile.Append("\t\t\t\t" + varType + ".TryParse(" + varName + "Array[i], out " + varName + "[i]);\n"); } } else if (varType.Equals("string")) { if (varLen == null) { //csFile += "\t\t\tif(sheet[row][column] == null)" + "\n"; csFile.Append("\t\t\t" + varName + " = sheet[row][column++] ?? \"" + /*varDefault + */ "\";\n"); //csFile += "\t\t\telse" + "\n"; //csFile += "\t\t\t\t" + varName + " = sheet[row][column];\n"; } else { csFile.Append("\t\t\tstring[] " + varName + "Array = sheet[row][column++].Split(\',\');" + "\n"); csFile.Append("\t\t\tint " + varName + "Count = " + varName + "Array.Length;" + "\n"); csFile.Append("\t\t\t" + varName + " = new " + varType + "[" + varName + "Count];\n"); csFile.Append("\t\t\tfor(int i = 0; i < " + varName + "Count; i++)\n"); csFile.Append("\t\t\t\t" + varName + "[i] = " + varName + "Array[i];\n"); } } } csFile.Append("\t\t\treturn column;\n"); csFile.Append("\t\t}\n#endif\n"); csFile.Append("\t}\n\n"); // DataTable class csFile.Append("\tpublic class " + dataTableClassName + " : RowDataCollection\n"); csFile.Append("\t{\n"); csFile.AppendFormat("\t\t[SerializeField]\n\t\tprivate List<{0}> elements = new List<{0}>();\n\n", rowDataClassName); csFile.AppendFormat("\t\tpublic override void AddData(RowData data)\n\t\t{{\n\t\t\telements.Add(data as {0});\n\t\t}}\n\n", rowDataClassName); csFile.Append("\t\tpublic override int GetDataCount()\n\t\t{\n\t\t\treturn elements.Count;\n\t\t}\n\n"); csFile.Append("\t\tpublic override RowData GetData(int index)\n\t\t{\n\t\t\treturn elements[index];\n\t\t}\n"); csFile.Append("\t}\n"); csFile.Append("}\n"); return(csFile.ToString()); } catch (Exception ex) { EELog.LogError(ex.ToString()); } return(""); }
private static void ToScriptableObject(string sheetName, string outputPath, SheetData sheetData) { try { var dataTableClassName = EESettings.Current.GetDataTableClassName(sheetName); var asset = ScriptableObject.CreateInstance(dataTableClassName); var dataCollect = asset as RowDataCollection; if (dataCollect == null) { return; } var className = EESettings.Current.GetRowDataClassName(sheetName, true); var dataType = Type.GetType(className); if (dataType == null) { var asmb = Assembly.LoadFrom(Environment.CurrentDirectory + "/Library/ScriptAssemblies/Assembly-CSharp.dll"); dataType = asmb.GetType(className); } if (dataType == null) { EELog.LogError(className + " not exist !"); return; } var dataCtor = dataType.GetConstructor(Type.EmptyTypes); if (dataCtor == null) { return; } var ids = new HashSet <int>(); for (var row = EESettings.Current.DataStartIndex; row < sheetData.rowCount; ++row) { for (var col = 0; col < sheetData.columnCount; ++col) { sheetData.Set(row, col, sheetData.Get(row, col).Replace("\n", "\\n")); } var inst = dataCtor.Invoke(null) as RowData; if (inst == null) { continue; } inst._init(sheetData.Table, row, 0); if (!ids.Contains(inst.ID)) { dataCollect.AddData(inst); ids.Add(inst.ID); } else { EELog.LogWarning("More than one rows use ID " + inst.ID + " in " + sheetName); } } var itemPath = outputPath + EESettings.GetAssetFileName(sheetName); itemPath = itemPath.Substring(itemPath.IndexOf("Assets", StringComparison.Ordinal)); AssetDatabase.CreateAsset(asset, itemPath); AssetDatabase.Refresh(); } catch (Exception ex) { EELog.LogError(ex.ToString()); } }