示例#1
0
        /// <summary>
        /// Generate AssetPostprocessor editor script file.
        /// </summary>
        protected override void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp)
        {
            ExcelMachine machine = target as ExcelMachine;

            sp.className          = machine.WorkSheetName;
            sp.dataClassName      = machine.WorkSheetName + "Data";
            sp.worksheetClassName = machine.WorkSheetName;

            // where the imported excel file is.
            sp.importedFilePath = machine.excelFilePath;

            // path where the .asset file will be created.
            string path = Path.GetDirectoryName(machine.excelFilePath);

            path += "/" + machine.WorkSheetName + ".asset";

            /*
             * @description 경로 문자열 변환
             */
            sp.assetFilepath           = path.Replace("\\", "/");
            sp.assetPostprocessorClass = machine.WorkSheetName + "AssetPostprocessor";
            sp.template = GetTemplate("PostProcessor");

            // write a script to the given folder.
            using (var writer = new StreamWriter(TargetPathForAssetPostProcessorFile(machine.WorkSheetName)))
            {
                writer.Write(new ScriptGenerator(sp).ToString());
                writer.Close();
            }
        }
示例#2
0
        /// <summary>
        /// Generate AssetPostprocessor editor script file.
        /// </summary>
        protected override void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp)
        {
            ExcelMachine machine = target as ExcelMachine;

            sp.className          = machine.WorkSheetName;
            sp.dataClassName      = machine.WorkSheetName + "Data";
            sp.worksheetClassName = machine.WorkSheetName;

            // where the imported excel file is.
            sp.importedFilePath = machine.excelFilePath;

            // path where the .asset file will be created.
            string path = ExcelSettings.Instance.AssetPath;

            if (string.IsNullOrEmpty(path))
            {
                Path.GetDirectoryName(machine.excelFilePath);
            }
            else
            {
                path = "Assets/" + path;
            }
            path                      += "/" + machine.WorkSheetName + ".asset";
            sp.assetFilepath           = path.Replace('\\', '/');
            sp.assetPostprocessorClass = machine.WorkSheetName + "AssetPostprocessor";
            sp.template                = GetTemplate("PostProcessor");

            // write a script to the given folder.
            using (var writer = new StreamWriter(TargetPathForAssetPostProcessorFile(machine.WorkSheetName)))
            {
                writer.Write(new ScriptGenerator(sp).ToString());
                writer.Close();
            }
        }
        public static void CreateScriptMachineAsset()
        {
            ExcelMachine inst = ScriptableObject.CreateInstance <ExcelMachine>();
            string       path = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(ImportSettingFilename);

            AssetDatabase.CreateAsset(inst, path);
            AssetDatabase.SaveAssets();
            Selection.activeObject = inst;
        }
        void CreateDataClassScript()
        {
            ExcelMachine machine = target as ExcelMachine;

#if UNITY_EDITOR_WIN
            var files = new DirectoryInfo(machine.fileFolder).GetFiles().Where(x => x.Extension == ".xlsx");
#else // for UNITY_EDITOR_OSX
            var files = new DirectoryInfo(machine.fileFolder).GetFiles().Where(x => x.Extension == ".xls");
#endif
            foreach (var fileInfo in files)
            {
                var className = Path.GetFileNameWithoutExtension(fileInfo.Name);
                // check the directory path exists
                var    targetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(target));
                string fullPath   = Path.Combine(targetPath + "/Runtime", className + "ExcelData." + "cs");
                string folderPath = Path.GetDirectoryName(fullPath);
                if (!Directory.Exists(folderPath))
                {
                    EditorUtility.DisplayDialog(
                        "Warning",
                        "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.",
                        "OK"
                        );
                    return;
                }

                string error   = string.Empty;
                var    titles  = new ExcelQuery(fileInfo.FullName, 0).GetTitle(2, ref error);
                var    types   = new ExcelQuery(fileInfo.FullName, 0).GetTitle(1, ref error);
                var    comment = new ExcelQuery(fileInfo.FullName, 0).GetTitle(0, ref error);

                List <MemberFieldData> fieldList = new List <MemberFieldData>();

                for (int i = 0; i < titles.Length; i++)
                {
                    MemberFieldData member = new MemberFieldData();
                    member.Name = titles[i];
                    member.type = MemberFieldData.GetType(types[i]);
                    fieldList.Add(member);
                }

                var sp = new ScriptPrescription
                {
                    className    = className + "ExcelData",
                    template     = GetTemplate("DataClass"),
                    memberFields = fieldList.ToArray()
                };

                // write a script to the given folder.
                using (var writer = new StreamWriter(fullPath))
                {
                    writer.Write(new ScriptGenerator(sp).ToString());
                    writer.Close();
                }
            }
        }
        protected void ImportAll()
        {
            ExcelMachine machine = target as ExcelMachine;

            foreach (var fileInfo in new DirectoryInfo(machine.fileFolder).GetFiles())
            {
                var path = fileInfo.FullName;

                if (string.IsNullOrEmpty(path))
                {
                    string msg = "You should specify spreadsheet file first!";
                    EditorUtility.DisplayDialog("Error", msg, "OK");
                    return;
                }

                if (!File.Exists(path))
                {
                    string msg = string.Format("File at {0} does not exist.", path);
                    EditorUtility.DisplayDialog("Error", msg, "OK");
                    return;
                }

                string error  = string.Empty;
                var    titles = new ExcelQuery(path, 0).GetTitle(2, ref error);
                if (titles == null || !string.IsNullOrEmpty(error))
                {
                    EditorUtility.DisplayDialog("Error", error, "OK");
                    return;
                }
                else
                {
                    // check the column header is valid
                    foreach (string column in titles)
                    {
                        if (!IsValidHeader(column))
                        {
                            error = string.Format(@"Invalid column header name {0}. Any c# keyword should not be used for column header. Note it is not case sensitive.", column);
                            EditorUtility.DisplayDialog("Error", error, "OK");
                            return;
                        }
                    }
                }

                List <string> titleList = titles.ToList();

                if (titleList.Count == 0)
                {
                    string msg = string.Format("An empty workhheet: [{0}] ", 0);
                    Debug.LogWarning(msg);
                }
            }

            EditorUtility.SetDirty(machine);
            AssetDatabase.SaveAssets();
        }
        void CreateScriptableObjectEditorClassScript()
        {
            ExcelMachine machine = target as ExcelMachine;

#if UNITY_EDITOR_WIN
            var files = new DirectoryInfo(machine.fileFolder).GetFiles().Where(x => x.Extension == ".xlsx");
#else // for UNITY_EDITOR_OSX
            var files = new DirectoryInfo(machine.fileFolder).GetFiles().Where(x => x.Extension == ".xls");
#endif
            foreach (var fileInfo in files)
            {
                var className = Path.GetFileNameWithoutExtension(fileInfo.Name);
                // check the directory path exists
                var    targetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(target));
                string fullPath   = Path.Combine(targetPath + "/Editor", className + "SOEditor." + "cs");
                string folderPath = Path.GetDirectoryName(fullPath);
                if (!Directory.Exists(folderPath))
                {
                    EditorUtility.DisplayDialog(
                        "Warning",
                        "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.",
                        "OK"
                        );
                    return;
                }

                var sp = new ScriptPrescription()
                {
                    className          = className + "SOEditor",
                    worksheetClassName = className + "SO",
                    dataClassName      = className + "ExcelData",
                    template           = GetTemplate("ScriptableObjectEditorClass"),
                };

                StreamWriter writer = null;
                try
                {
                    // write a script to the given folder.
                    writer = new StreamWriter(fullPath);
                    writer.Write(new ScriptGenerator(sp).ToString());
                }
                catch (System.Exception e)
                {
                    Debug.LogError(e);
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                        writer.Dispose();
                    }
                }
            }
        }
示例#7
0
        private static void RenameMachineAsset(ExcelMachine machine)
        {
            var name = new StringBuilder();

            name.Append(machine.SpreadSheetName.Split('.')[0])
            .Append("-")
            .Append(machine.WorkSheetName)
            .Append("-")
            .Append("Importer");
            var err = AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(machine), name.ToString());

            if (!string.IsNullOrEmpty(err))
            {
                Debug.LogWarning("Rename failed " + err);
            }
        }
        void CreateAssetCreationScript()
        {
            ExcelMachine machine = target as ExcelMachine;

#if UNITY_EDITOR_WIN
            var files = new DirectoryInfo(machine.fileFolder).GetFiles().Where(x => x.Extension == ".xlsx");
#else // for UNITY_EDITOR_OSX
            var files = new DirectoryInfo(machine.fileFolder).GetFiles().Where(x => x.Extension == ".xls");
#endif
            foreach (var fileInfo in files)
            {
                var className = Path.GetFileNameWithoutExtension(fileInfo.Name);
                // check the directory path exists
                var    targetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(target));
                string fullPath   = Path.Combine(targetPath + "/Editor", className + "AP." + "cs");
                string folderPath = Path.GetDirectoryName(fullPath);
                if (!Directory.Exists(folderPath))
                {
                    EditorUtility.DisplayDialog(
                        "Warning",
                        "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.",
                        "OK"
                        );
                    return;
                }

                var sp = new ScriptPrescription
                {
                    className     = className + "SO",
                    dataClassName = className + "ExcelData",

                    // where the imported excel file is.
                };
                sp.importedFilePath        = fileInfo.FullName.Replace("\\", "/");
                sp.importedFilePath        = sp.importedFilePath.Substring(sp.importedFilePath.IndexOf("Assets/"));
                sp.assetFilepath           = Path.GetDirectoryName(AssetDatabase.GetAssetPath(target)).Replace("\\", "/") + "/Data/" + className + ".asset";
                sp.assetPostprocessorClass = className + "AssetPostprocessor";
                sp.template = GetTemplate("PostProcessor");

                // write a script to the given folder.
                using (var writer = new StreamWriter(fullPath))
                {
                    writer.Write(new ScriptGenerator(sp).ToString());
                    writer.Close();
                }
            }
        }
示例#9
0
        public static void SetupSelectExcels()
        {
            if (Selection.assetGUIDs.Length == 0)
            {
                EditorUtility.DisplayDialog("Error", "Select excel files to setup!", "OK");
                return;
            }

            var selectObjs = new List <Object>();

            foreach (var guid in Selection.assetGUIDs)
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);
                if (!IsExcel(path))
                {
                    continue;
                }

                ExcelSettings.Instance._waitImportPath.Add(path);

                var excelQuery = new ExcelQuery(path);
                var sheets     = excelQuery.GetSheetNames();
                for (int i = 0; i < sheets.Length; i++)
                {
                    var machine = ExcelMachine.CreateScriptMachineAsset();
                    machine.excelFilePath     = path;
                    machine.SheetNames        = sheets;
                    machine.WorkSheetName     = sheets[i];
                    machine.CurrentSheetIndex = i;
                    machine.SpreadSheetName   = Path.GetFileName(path);

                    ReimportMachine(machine, true);
                    BaseMachineEditor.CreateGenerateDirectory(machine);
                    GenerateMachine(machine, false);
                    RenameMachineAsset(machine);

                    selectObjs.Add(machine);
                    Debug.LogFormat("Setup finished! file:{0}, Sheet:{1}", machine.SpreadSheetName, sheets[i]);
                }
            }

            Selection.objects = selectObjs.ToArray();
            AssetDatabase.Refresh();
        }
示例#10
0
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            ExcelMachine machine = target as ExcelMachine;

            GUILayout.Label("Excel Spreadsheet Settings:", headerStyle);

            GUILayout.BeginHorizontal();
            GUILayout.Label("File:", GUILayout.Width(50));

            string path = string.Empty;

            if (string.IsNullOrEmpty(machine.excelFilePath))
            {
                path = Application.dataPath;
            }
            else
            {
                path = machine.excelFilePath;
            }

            machine.excelFilePath = GUILayout.TextField(path, GUILayout.Width(250));
            if (GUILayout.Button("...", GUILayout.Width(20)))
            {
                string folder = Path.GetDirectoryName(path);
#if UNITY_EDITOR_WIN
                path = EditorUtility.OpenFilePanel("Open Excel file", folder, "excel files;*.xls;*.xlsx");
#else // for UNITY_EDITOR_OSX
                path = EditorUtility.OpenFilePanel("Open Excel file", folder, "xls");
#endif
                if (path.Length != 0)
                {
                    machine.SpreadSheetName = Path.GetFileName(path);

                    // the path should be relative not absolute one to make it work on any platform.
                    int index = path.IndexOf("Assets");
                    if (index >= 0)
                    {
                        // set relative path
                        machine.excelFilePath = path.Substring(index);

                        // pass absolute path
                        machine.SheetNames = new ExcelQuery(path).GetSheetNames();
                    }
                    else
                    {
                        EditorUtility.DisplayDialog("Error",
                                                    @"Wrong folder is selected.
                        Set a folder under the 'Assets' folder! \n
                        The excel file should be anywhere under  the 'Assets' folder", "OK");
                        return;
                    }
                }
            }
            GUILayout.EndHorizontal();

            // Failed to get sheet name so we just return not to make editor on going.
            if (machine.SheetNames.Length == 0)
            {
                EditorGUILayout.Separator();
                EditorGUILayout.LabelField("Error: Failed to retrieve the specified excel file.");
                EditorGUILayout.LabelField("If the excel file is opened, close it then reopen it again.");
                return;
            }

            // spreadsheet name should be read-only
            EditorGUILayout.TextField("Spreadsheet File: ", machine.SpreadSheetName);

            EditorGUILayout.Space();

            using (new GUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Worksheet: ", GUILayout.Width(100));
                machine.CurrentSheetIndex = EditorGUILayout.Popup(machine.CurrentSheetIndex, machine.SheetNames);
                if (machine.SheetNames != null)
                {
                    machine.WorkSheetName = machine.SheetNames[machine.CurrentSheetIndex];
                }

                if (GUILayout.Button("Refresh", GUILayout.Width(60)))
                {
                    // reopen the excel file e.g) new worksheet is added so need to reopen.
                    machine.SheetNames = new ExcelQuery(machine.excelFilePath).GetSheetNames();

                    // one of worksheet was removed, so reset the selected worksheet index
                    // to prevent the index out of range error.
                    if (machine.SheetNames.Length <= machine.CurrentSheetIndex)
                    {
                        machine.CurrentSheetIndex = 0;

                        string message = "Worksheet was changed. Check the 'Worksheet' and 'Update' it again if it is necessary.";
                        EditorUtility.DisplayDialog("Info", message, "OK");
                    }
                }
            }

            EditorGUILayout.Separator();

            GUILayout.BeginHorizontal();

            if (machine.HasColumnHeader())
            {
                if (GUILayout.Button("Update"))
                {
                    Import();
                }
                if (GUILayout.Button("Reimport"))
                {
                    Import(true);
                }
            }
            else
            {
                if (GUILayout.Button("Import"))
                {
                    Import();
                }
            }

            GUILayout.EndHorizontal();

            EditorGUILayout.Separator();

            DrawHeaderSetting(machine);

            EditorGUILayout.Separator();

            GUILayout.Label("Path Settings:", headerStyle);

            machine.TemplatePath     = EditorGUILayout.TextField("Template: ", machine.TemplatePath);
            machine.RuntimeClassPath = EditorGUILayout.TextField("Runtime: ", machine.RuntimeClassPath);
            machine.EditorClassPath  = EditorGUILayout.TextField("Editor:", machine.EditorClassPath);
            //machine.DataFilePath = EditorGUILayout.TextField("Data:", machine.DataFilePath);

            machine.onlyCreateDataClass = EditorGUILayout.Toggle("Only DataClass", machine.onlyCreateDataClass);

            EditorGUILayout.Separator();

            if (GUILayout.Button("Generate"))
            {
                if (string.IsNullOrEmpty(machine.SpreadSheetName) || string.IsNullOrEmpty(machine.WorkSheetName))
                {
                    Debug.LogWarning("No spreadsheet or worksheet is specified.");
                    return;
                }

                Directory.CreateDirectory(Application.dataPath + Path.DirectorySeparatorChar + machine.RuntimeClassPath);
                Directory.CreateDirectory(Application.dataPath + Path.DirectorySeparatorChar + machine.EditorClassPath);

                ScriptPrescription sp = Generate(machine);
                if (sp != null)
                {
                    Debug.Log("Successfully generated!");
                }
                else
                {
                    Debug.LogError("Failed to create a script from excel.");
                }
            }

            if (GUI.changed)
            {
                EditorUtility.SetDirty(machine);
            }
        }
示例#11
0
        /// <summary>
        /// Import the specified excel file and prepare to set type of each cell.
        /// </summary>
        protected override void Import(bool reimport = false)
        {
            ExcelMachine machine = target as ExcelMachine;

            string path  = machine.excelFilePath;
            string sheet = machine.WorkSheetName;

            if (string.IsNullOrEmpty(path))
            {
                string msg = "You should specify spreadsheet file first!";
                EditorUtility.DisplayDialog("Error", msg, "OK");
                return;
            }

            if (!File.Exists(path))
            {
                string msg = string.Format("File at {0} does not exist.", path);
                EditorUtility.DisplayDialog("Error", msg, "OK");
                return;
            }

            int    startRowIndex = 0;
            string error         = string.Empty;
            var    titles        = new ExcelQuery(path, sheet).GetTitle(startRowIndex, ref error);

            if (titles == null || !string.IsNullOrEmpty(error))
            {
                EditorUtility.DisplayDialog("Error", error, "OK");
                return;
            }
            else
            {
                // check the column header is valid
                foreach (string column in titles)
                {
                    if (!IsValidHeader(column))
                    {
                        error = string.Format(@"Invalid column header name {0}. Any c# keyword should not be used for column header. Note it is not case sensitive.", column);
                        EditorUtility.DisplayDialog("Error", error, "OK");
                        return;
                    }
                }
            }

            List <string> titleList = titles.ToList();

            if (machine.HasColumnHeader() && reimport == false)
            {
                var headerDic = machine.ColumnHeaderList.ToDictionary(header => header.name);

                // collect non-changed column headers
                var exist = titleList.Select(t => GetColumnHeaderString(t))
                            .Where(e => headerDic.ContainsKey(e) == true)
                            .Select(t => new ColumnHeader {
                    name = t, type = headerDic[t].type, isArray = headerDic[t].isArray, OrderNO = headerDic[t].OrderNO
                });


                // collect newly added or changed column headers
                var changed = titleList.Select(t => GetColumnHeaderString(t))
                              .Where(e => headerDic.ContainsKey(e) == false)
                              .Select(t => ParseColumnHeader(t, titleList.IndexOf(t)));

                // merge two list via LINQ
                var merged = exist.Union(changed).OrderBy(x => x.OrderNO);

                machine.ColumnHeaderList.Clear();
                machine.ColumnHeaderList = merged.ToList();
            }
            else
            {
                machine.ColumnHeaderList.Clear();
                if (titleList.Count > 0)
                {
                    int order = 0;
                    machine.ColumnHeaderList = titleList.Select(e => ParseColumnHeader(e, order++)).ToList();
                }
                else
                {
                    string msg = string.Format("An empty workhheet: [{0}] ", sheet);
                    Debug.LogWarning(msg);
                }
            }

            EditorUtility.SetDirty(machine);
            AssetDatabase.SaveAssets();
        }
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            ExcelMachine machine = target as ExcelMachine;

            GUILayout.Label("Excel Settings:", headerStyle);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Folder:", GUILayout.Width(50));

            string path = string.Empty;

            if (string.IsNullOrEmpty(machine.fileFolder))
            {
                path = Application.dataPath;
            }
            else
            {
                path = machine.fileFolder;
            }

            machine.fileFolder = GUILayout.TextField(path, GUILayout.Width(250));
            if (GUILayout.Button("...", GUILayout.Width(20)))
            {
                string folder = Path.GetDirectoryName(path);
#if UNITY_EDITOR_WIN
                path = EditorUtility.OpenFolderPanel("Open Excel file folder", folder, string.Empty);
#else // for UNITY_EDITOR_OSX
                path = EditorUtility.OpenFolderPanel("Open Excel file folder", folder, string.Empty);
#endif
                if (path.Length != 0)
                {
                    var dirInfo = new DirectoryInfo(path);
                    if (dirInfo.Exists)
                    {
                        int index = path.IndexOf("Assets");
                        if (index >= 0)
                        {
                            // set relative path
                            machine.fileFolder = path.Substring(index);
                        }
                        else
                        {
                            EditorUtility.DisplayDialog("Error",
                                                        @"Wrong folder is selected.
                        Set a folder under the 'Assets' folder! \n
                        The excel file should be anywhere under  the 'Assets' folder", "OK");
                            return;
                        }
                    }
                }
            }
            GUILayout.EndHorizontal();

            EditorGUILayout.Separator();

            GUILayout.Label("Path Settings:", headerStyle);

            machine.TemplatePath = EditorGUILayout.TextField("Template: ", machine.TemplatePath);

            EditorGUILayout.Separator();

            GUILayout.BeginHorizontal();

            if (GUILayout.Button("Import"))
            {
                var targetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(target));
                if (!AssetDatabase.IsValidFolder(targetPath + "/Runtime"))
                {
                    AssetDatabase.CreateFolder(targetPath, "Runtime");
                }
                if (!AssetDatabase.IsValidFolder(targetPath + "/Editor"))
                {
                    AssetDatabase.CreateFolder(targetPath, "Editor");
                }
                if (!AssetDatabase.IsValidFolder(targetPath + "/Data"))
                {
                    AssetDatabase.CreateFolder(targetPath, "Data");
                }

                CreateScriptableObjectClassScript();
                CreateScriptableObjectEditorClassScript();
                CreateDataClassScript();
                CreateAssetCreationScript();

                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();

                Debug.Log("Excel Done!");
            }

            if (GUILayout.Button("Generate"))
            {
                var assets = AssetDatabase.FindAssets(string.Empty, new string[] { machine.fileFolder });
                foreach (var item in assets)
                {
                    AssetDatabase.ImportAsset(AssetDatabase.GUIDToAssetPath(item));
                }
            }

            GUILayout.EndHorizontal();

            if (GUI.changed)
            {
                EditorUtility.SetDirty(machine);
            }
        }
        /// <summary>
        /// Import the specified excel file and prepare to set type of each cell.
        /// </summary>
        protected override void Import(bool reimport = false)
        {
            base.Import(reimport);

            ExcelMachine machine = target as ExcelMachine;

            string path  = machine.excelFilePath;
            string sheet = machine.WorkSheetName;

            if (string.IsNullOrEmpty(path))
            {
                EditorUtility.DisplayDialog(
                    "Error",
                    "You should specify spreadsheet file first!",
                    "OK"
                    );
                return;
            }

            if (!File.Exists(path))
            {
                EditorUtility.DisplayDialog(
                    "Error",
                    "File at " + path + " does not exist.",
                    "OK"
                    );
                return;
            }

            var           titles    = new ExcelQuery(path, sheet).GetTitle();
            List <string> titleList = titles.ToList();

            if (machine.HasHeadColumn() && reimport == false)
            {
                var headerDic = machine.HeaderColumnList.ToDictionary(header => header.name);

                // collect non changed header columns
                var exist = from t in titleList
                            where headerDic.ContainsKey(t) == true
                            select new HeaderColumn {
                    name = t, type = headerDic[t].type, OrderNO = headerDic[t].OrderNO
                };

                // collect newly added or changed header columns
                var changed = from t in titleList
                              where headerDic.ContainsKey(t) == false
                              select new HeaderColumn {
                    name = t, type = CellType.Undefined, OrderNO = titleList.IndexOf(t)
                };

                // merge two
                var merged = exist.Union(changed).OrderBy(x => x.OrderNO);

                machine.HeaderColumnList.Clear();
                machine.HeaderColumnList = merged.ToList();
            }
            else
            {
                machine.HeaderColumnList.Clear();

                if (titles != null)
                {
                    int i = 0;
                    foreach (string s in titles)
                    {
                        machine.HeaderColumnList.Add(new HeaderColumn {
                            name = s, type = CellType.Undefined, OrderNO = i
                        });
                        i++;
                    }
                }
                else
                {
                    Debug.LogWarning("The WorkSheet [" + sheet + "] may be empty.");
                }
            }

            EditorUtility.SetDirty(machine);
            AssetDatabase.SaveAssets();
        }
示例#14
0
        /// <summary>
        /// Import the specified excel file and prepare to set type of each cell.
        /// </summary>
        protected override void Import(bool reimport = false)
        {
            ExcelMachine machine = target as ExcelMachine;

            string path  = machine.excelFilePath;
            string sheet = machine.WorkSheetName;

            if (string.IsNullOrEmpty(path))
            {
                EditorUtility.DisplayDialog(
                    "Error",
                    "You should specify spreadsheet file first!",
                    "OK"
                    );
                return;
            }

            if (!File.Exists(path))
            {
                EditorUtility.DisplayDialog(
                    "Error",
                    "File at " + path + " does not exist.",
                    "OK"
                    );
                return;
            }

            int    startRowIndex = 0;
            string error         = string.Empty;
            var    titles        = new ExcelQuery(path, sheet).GetTitle(startRowIndex, ref error);

            if (titles == null || !string.IsNullOrEmpty(error))
            {
                EditorUtility.DisplayDialog("Error", error, "OK");
                return;
            }
            else
            {
                // check the column header is valid
                foreach (string column in titles)
                {
                    if (!IsValidHeader(column))
                    {
                        error = string.Format(@"Invalid column header name {0}. Any c# keyword should not be used for column header. Note it is not case sensitive.", column);
                        EditorUtility.DisplayDialog("Error", error, "OK");
                        return;
                    }
                }
            }

            List <string> titleList = titles.ToList();

            if (machine.HasColumnHeader() && reimport == false)
            {
                var headerDic = machine.ColumnHeaderList.ToDictionary(header => header.name);

                // collect non-changed column headers
                var exist = from t in titleList
                            where headerDic.ContainsKey(t) == true
                            select new ColumnHeader {
                    name = t, type = headerDic[t].type, isArray = headerDic[t].isArray, OrderNO = headerDic[t].OrderNO
                };

                // collect newly added or changed column headers
                var changed = from t in titleList
                              where headerDic.ContainsKey(t) == false
                              select new ColumnHeader {
                    name = t, type = CellType.Undefined, OrderNO = titleList.IndexOf(t)
                };

                // merge two list via LINQ
                var merged = exist.Union(changed).OrderBy(x => x.OrderNO);

                machine.ColumnHeaderList.Clear();
                machine.ColumnHeaderList = merged.ToList();
            }
            else
            {
                machine.ColumnHeaderList.Clear();

                if (titles != null)
                {
                    int i = 0;
                    foreach (string s in titles)
                    {
                        machine.ColumnHeaderList.Add(new ColumnHeader {
                            name = s, type = CellType.Undefined, OrderNO = i
                        });
                        i++;
                    }
                }
                else
                {
                    Debug.LogWarning("The WorkSheet [" + sheet + "] may be empty.");
                }
            }

            EditorUtility.SetDirty(machine);
            AssetDatabase.SaveAssets();
        }
示例#15
0
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            ExcelMachine machine = target as ExcelMachine;

            GUILayout.Label("Excel Spreadsheet Settings:", headerStyle);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Template Excel:", GUILayout.Width(90));
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();

            string path = string.Empty;

            if (string.IsNullOrEmpty(machine.excelFilePath))
            {
                path = Application.dataPath;
            }
            else
            {
                path = machine.excelFilePath;
            }

            machine.excelFilePath = GUILayout.TextField(path, GUILayout.Width(250));
            if (GUILayout.Button("...", GUILayout.Width(20)))
            {
                path = OpenExcelFilePanel(path);

                if (path.Length != 0)
                {
                    // the path should be relative not absolute one to make it work on any platform.
                    string trimPath = TrimToRelativePath(path);
                    if (!string.IsNullOrEmpty(trimPath))
                    {
                        // set relative path
                        machine.excelFilePath = trimPath;

                        // pass absolute path
                        machine.SheetNames = new ExcelQuery(path).GetSheetNames();
                    }
                    else
                    {
                        EditorUtility.DisplayDialog("Error",
                                                    @"Wrong folder is selected.
                        Set a folder under the 'Assets' folder! \n
                        The excel file should be anywhere under  the 'Assets' folder", "OK");
                        return;
                    }
                }
            }

            GUILayout.EndHorizontal();

            // Failed to get sheet name so we just return not to make editor on going.
            if (machine.SheetNames.Length == 0)
            {
                EditorGUILayout.Separator();
                EditorGUILayout.LabelField("Error: Failed to retrieve the specified excel file.");
                EditorGUILayout.LabelField("If the excel file is opened, close it then reopen it again.");
                return;
            }

            // begin: add excel export path
            GUILayout.BeginHorizontal();
            GUILayout.Label("Export Folder:", GUILayout.Width(100));
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();

            string exportPath = string.Empty;

            if (string.IsNullOrEmpty(machine.exportFilePath))
            {
                exportPath = Application.dataPath;
            }
            else
            {
                exportPath = machine.exportFilePath;
            }

            machine.exportFilePath = GUILayout.TextField(exportPath, GUILayout.Width(250));

            if (GUILayout.Button("...", GUILayout.Width(20)))
            {
                string folder = Path.GetDirectoryName(exportPath);
#if UNITY_EDITOR_WIN
                exportPath = EditorUtility.OpenFilePanel("Open Excel file", folder, "excel files;*.xls;*.xlsx");
#else // for UNITY_EDITOR_OSX
                exportPath = EditorUtility.OpenFolderPanel("Open Excel file", folder, "xls");
#endif
                if (exportPath.Length != 0)
                {
                    // the path should be relative not absolute one to make it work on any platform.
                    int index = exportPath.IndexOf("Assets");
                    if (index >= 0)
                    {
                        // set relative path
                        machine.exportFilePath = exportPath.Substring(index);
                    }
                    else
                    {
                        EditorUtility.DisplayDialog("Error",
                                                    @"Wrong folder is selected.
                        Set a folder under the 'Assets' folder! \n
                        The excel file should be anywhere under  the 'Assets' folder", "OK");
                        return;
                    }
                }
            }

            GUILayout.EndHorizontal();
            EditorGUILayout.Separator();
            // end: add excel export path

            EditorGUILayout.Space();

            using (new GUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Worksheet: ", GUILayout.Width(100));
                machine.CurrentSheetIndex = EditorGUILayout.Popup(machine.CurrentSheetIndex, machine.SheetNames);
                if (machine.SheetNames != null)
                {
                    machine.WorkSheetName = machine.SheetNames[machine.CurrentSheetIndex];
                }

                if (GUILayout.Button("Refresh", GUILayout.Width(60)))
                {
                    // reopen the excel file e.g) new worksheet is added so need to reopen.
                    machine.SheetNames = new ExcelQuery(machine.excelFilePath).GetSheetNames();

                    // one of worksheet was removed, so reset the selected worksheet index
                    // to prevent the index out of range error.
                    if (machine.SheetNames.Length <= machine.CurrentSheetIndex)
                    {
                        machine.CurrentSheetIndex = 0;

                        string message = "Worksheet was changed. Check the 'Worksheet' and 'Update' it again if it is necessary.";
                        EditorUtility.DisplayDialog("Info", message, "OK");
                    }
                }
            }

            EditorGUILayout.Separator();

            GUILayout.BeginHorizontal();

            if (machine.HasColumnHeader(machine.WorkSheetName))
            {
                if (GUILayout.Button("Update"))
                {
                    Import();
                }
                if (GUILayout.Button("Reimport"))
                {
                    Import(true);
                }
            }
            else
            {
                if (GUILayout.Button("Import"))
                {
                    Import();
                }
            }

            GUILayout.EndHorizontal();

            EditorGUILayout.Separator();

            ColumnHeaderList curSheetConfig = machine.GetCurrentWorkSheetConfig();
            curSheetConfig.IsReuseOtherSheet = EditorGUILayout.Toggle("Is Reuse Other Sheet", curSheetConfig.IsReuseOtherSheet);

            if (curSheetConfig.IsReuseOtherSheet)
            {
                curSheetConfig.ReuseSheetName = EditorGUILayout.TextField("Reuse Sheet Name: ", curSheetConfig.ReuseSheetName);
            }

            EditorGUILayout.Separator();

            DrawHeaderSetting(machine);

            EditorGUILayout.Separator();

            curSheetConfig.onlyCreatePostProcessClass = EditorGUILayout.Toggle("Only Gen PostProcessor", curSheetConfig.onlyCreatePostProcessClass);

            //
            //Generate button
            //
            if (GUILayout.Button("Generate Scripts"))
            {
                ScriptPrescription sp = Generate(machine);
                if (sp != null)
                {
                    Debug.Log("Successfully generated!");
                }
                else
                {
                    Debug.LogError("Failed to create a script from excel.");
                }
            }

            EditorGUILayout.Separator();

            GUILayout.BeginHorizontal();

            //
            //Import Excels
            //
            GUILayout.Label("Import Excels:", headerStyle);

            GUILayout.EndHorizontal();

            for (int i = 0; i < machine.importFileList.Count; i++)
            {
                GUILayout.BeginHorizontal();

                string importFile = machine.importFileList[i];

                importFile = GUILayout.TextField(importFile, GUILayout.Width(200));

                if (GUILayout.Button("...", GUILayout.Width(20)))
                {
                    if (string.IsNullOrEmpty(importFile))
                    {
                        importFile = Application.dataPath;
                    }

                    path = OpenExcelFilePanel(importFile);

                    if (path.Length != 0)
                    {
                        // the path should be relative not absolute one to make it work on any platform.
                        string trimPath = TrimToRelativePath(path);
                        if (!string.IsNullOrEmpty(trimPath))
                        {
                            // set relative path
                            machine.importFileList[i] = trimPath;
                        }
                        else
                        {
                            EditorUtility.DisplayDialog("Error",
                                                        @"Wrong folder is selected.
                        Set a folder under the 'Assets' folder! \n
                        The excel file should be anywhere under  the 'Assets' folder", "OK");
                            return;
                        }
                    }
                }

                if (GUILayout.Button("-", GUILayout.Width(20)))
                {
                    machine.importFileList.RemoveAt(i);
                }

                if (GUILayout.Button("+", GUILayout.Width(20)))
                {
                    machine.importFileList.Insert(i + 1, "");
                }

                if (GUILayout.Button("Export", GUILayout.Width(48)))
                {
                    ImportExcelFile(machine.importFileList[i]);
                }

                GUILayout.EndHorizontal();
            }

            if (GUILayout.Button("Export All", GUILayout.Width(80)))
            {
                foreach (string filePath in machine.importFileList)
                {
                    ImportExcelFile(filePath);
                }
            }

            EditorGUILayout.Separator();

            GUILayout.Label("Path Settings:", headerStyle);

            machine.TemplatePath     = EditorGUILayout.TextField("Template: ", machine.TemplatePath);
            machine.RuntimeClassPath = EditorGUILayout.TextField("Runtime: ", machine.RuntimeClassPath);
            machine.EditorClassPath  = EditorGUILayout.TextField("Editor:", machine.EditorClassPath);
            //machine.DataFilePath = EditorGUILayout.TextField("Data:", machine.DataFilePath);

            if (GUI.changed)
            {
                EditorUtility.SetDirty(machine);
                //AssetDatabase.SaveAssets();
                //AssetDatabase.Refresh();
            }
        }