static void ImportExcel(string excelPath, ExcelAssetInfo info) { string assetPath = ""; string assetName = info.AssetType.Name + ".asset"; if (string.IsNullOrEmpty(info.Attribute.AssetPath)) { string basePath = Path.GetDirectoryName(excelPath); assetPath = Path.Combine(basePath, assetName); } else { var path = Path.Combine("Assets", info.Attribute.AssetPath); assetPath = Path.Combine(path, assetName); } UnityEngine.Object asset = LoadOrCreateAsset(assetPath, info.AssetType); //Debug.Log(info.AssetType.GetFields()[0].Attributes); IWorkbook book = LoadBook(excelPath); //Debug.Log(info.AssetType.GetFields()); var assetFields = info.AssetType.GetFields(); //读进来了 int sheetCount = 0; foreach (var assetField in assetFields) { ISheet sheet = book.GetSheet(assetField.Name); if (sheet == null) { continue; } Type fieldType = assetField.FieldType; if (!fieldType.IsGenericType || (fieldType.GetGenericTypeDefinition() != typeof(List <>))) { continue; } Type[] types = fieldType.GetGenericArguments(); Type entityType = types[0]; object entities = GetEntityListFromSheet(sheet, entityType); assetField.SetValue(asset, entities); sheetCount++; } if (info.Attribute.LogOnImport) { Debug.Log(string.Format("Imported {0} sheets form {1}.", sheetCount, excelPath)); } EditorUtility.SetDirty(asset); }
static List <ExcelAssetInfo> cachedInfos = null; // Clear on compile. static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { bool imported = false; foreach (string path in importedAssets) { if (Path.GetExtension(path) == ".xls" || Path.GetExtension(path) == ".xlsx") { if (cachedInfos == null) { cachedInfos = FindExcelAssetInfos(); } var excelName = Path.GetFileNameWithoutExtension(path); if (excelName.StartsWith("~$")) { continue; } ExcelAssetInfo info = cachedInfos.Find(i => i.ExcelName == excelName); if (info == null) { continue; } ImportExcel(path, info); imported = true; } } if (imported) { AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } }
static List <ExcelAssetInfo> FindExcelAssetInfos() { var list = new List <ExcelAssetInfo>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { foreach (var type in assembly.GetTypes()) { var attributes = type.GetCustomAttributes(typeof(ExcelAssetAttribute), false); if (attributes.Length == 0) { continue; } var attribute = (ExcelAssetAttribute)attributes[0]; var info = new ExcelAssetInfo() { AssetType = type, Attribute = attribute }; list.Add(info); } } return(list); }