unity 读取excel表 生成asset资源文件

unity 读取excel表 生成asset资源文件

 

这是第一篇在这里发表的文章。希望能够对需要的人有所帮助,我也是在自己项目中用的。说归说直接上代码:



 *导入excel,解析xml,生成c#数据表,生成asset数据文件 
 *原理 在导入xml文件的时候通过XmlReader读取xml文件 
 *把需要的内容按照读取的顺序保存,然后在生成key,最后生成key,value格式,然后自己手动定义要保存的内容数据格式最后通过自定义的数据格式生成数据文件 


复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
using  UnityEngine;
using  System.Collections;
using  UnityEditor;
using  System.Xml;
   
using  System;
using  System.Collections.Generic;
   
   
public  class  ExcekControl : AssetPostprocessor {
     static  string  FILE_PATH =  "Assets\\Data\\" ;
   
     /** 在导入所有资源之后 */
     static  void  OnPostprocessAllAssets( string [] importedAssets,  string [] deletedAssets,  string [] movedAssets,  string [] movedFromAssetPaths){
         string  excelPath =  "" ;
         for  ( int  i = 0; i < importedAssets.Length; i++) {
             /** 拦截Assets/Excel目录下面所有.xml文件进行解析 */
             excelPath = importedAssets[i];
             if (excelPath.Contains( ".xml" ))
             {
                 ReadXml(excelPath);
                 Debug.Log( "Excel import asset path : "  + excelPath);
             }
         }
     }
   
     static  void  ReadXml( string  xmlPath)
     {
         /** 读取xml 文件 */
         XmlReader xReader =  null ;
         try {
             xReader = XmlReader.Create(xmlPath);
         }
         catch (Exception e){
             Debug.LogError( "Read Excel Error! Path = "  + xmlPath);
         }
         if  (xReader ==  null ) {
             return ;    
         }
   
         /** 保存所有数据到表中 */
         List<xmlSheetList> xmlDataList =  new  List<xmlSheetList> ();
         xmlSheetList xsl =  null ;
   
         /** 记录每个节点的开始 */
         bool  sheetBegin =  false ;
         bool  rowBegin =  false ;
         bool  cellBegin =  false ;
         bool  dataBegin =  false ;
   
         /** 行数 */
         int  rowNum = 0;
         /** 列数 */
         int  cellNum = 0;
         /** 计数器 */
         int  num = 0;
         while  (xReader.Read ()) {
             string  name = xReader.Name;
             if (name ==  "Worksheet" )
             {
                 /** 开始 */
                 if (xReader.NodeType == XmlNodeType.Element)
                 {
                     sheetBegin =  true ;
                     /** xmlSheet */
                     xsl =  new  xmlSheetList();
                     xsl.Clear();
                 }
                 /** 结束 */
                 else  if (xReader.NodeType == XmlNodeType.EndElement){
                     sheetBegin =  false ;
                     xmlDataList.Add(xsl);
                 }
             }
             else  if (name ==  "Row" )
             {
                 /** 开始 */
                 if (xReader.NodeType == XmlNodeType.Element)
                 {
                     rowBegin =  true ;
                     rowNum++;
                 }
                 /** 结束 */
                 else  if (xReader.NodeType == XmlNodeType.EndElement){
                     rowBegin =  false ;
                 }
             }
             else  if (name ==  "Cell" ){
                 /** 开始 */
                 if (xReader.NodeType == XmlNodeType.Element)
                 {
                     cellBegin =  true ;
                     if (rowNum == 1)
                     {
                         cellNum++;
                     }
                     if (! string .IsNullOrEmpty(xReader.GetAttribute( "ss:Index" )))
                     {
   
                         Debug.LogError( string .Format( "xml read error! may be empty! : {0}  Row = {1} Cell = {2}." , xmlPath, ( int )(num / cellNum), ((num % cellNum)+1)));
                         return ;
                     }
                 }
                 /** 结束 */
                 else  if (xReader.NodeType == XmlNodeType.EndElement){
                     cellBegin =  false ;
                 }
             }
             else  if (name ==  "Data" ){
                 /** 开始 */
                 if (xReader.NodeType == XmlNodeType.Element)
                 {
                     dataBegin =  true ;
                 }
                 /** 结束 */
                 else  if (xReader.NodeType == XmlNodeType.EndElement){
                     dataBegin =  false ;
                 }
             }
             else {
                 /** 过滤数据 */
                 if (sheetBegin && rowBegin && cellBegin && dataBegin)
                 {
                     num++;
                     if (xsl !=  null )
                     {
                         xsl.Add(xReader.Value);
                     }
                 }
             }
         }
         int  an = xmlDataList.Count;
         int  bn = 0;
   
         List< string > keys =  new  List< string > ();
         for  ( int  i = 0; i < xmlDataList.Count; i++) {
             bn = xmlDataList[i].sheetList.Count;
             for ( int  k = 0; k < bn; k++)
             {
                 if (k < cellNum * 2)
                 {
                     if (k >= cellNum)
                     {
                         if (i == 0)
                         {
                             keys.Add(xmlDataList[i].sheetList[0]);
                         }
                     }
                     xmlDataList[i].sheetList.RemoveAt(0);
                 } else {
                     break ;
                 }
             }
         }
       
         List<Row> rowList =  new  List<Row> ();
         for ( int  k = 0; k < xmlDataList.Count; k++)
         {
             for ( int  i = 0; i < xmlDataList[k].sheetList.Count / cellNum; i++)
             {
                 Row row =  new  Row();
                 row._key = keys;
                 row._cells.Add(xmlDataList[k].sheetList[i * 3]);
                 row._cells.Add(xmlDataList[k].sheetList[i * 3 + 1]);
                 row._cells.Add(xmlDataList[k].sheetList[i * 3 + 2]);
                 rowList.Add(row);
             }
         }
         /** 创建资源 */
         CreatXmlListAsset (rowList, xmlPath);
     }
   
     /** 生成数据文件 */
     static  void  CreatXmlListAsset(List<Row> rl,  string  xmlPath)
     {
         if  (xmlPath.Contains ( "ActorData.xml" )) {
             GActorDataList actorDataList =  null ;
               
             UnityEngine.Object oldFile = AssetDatabase.LoadAssetAtPath (xmlPath,  typeof (GActorDataList));
             bool  newFile =  false ;
             if  (oldFile) {
                 actorDataList = oldFile  as  GActorDataList;
             } else {
                 actorDataList =  new  GActorDataList();
                 newFile =  true ;
             }
             actorDataList.ActorDataList.Clear ();
               
             for  ( int  i = 0; i < rl.Count; i++) {
                 ActorData newData =  new  ActorData();
                 Row data = rl[i];
                 newData.id = data[ "id" ];
                 newData.type = GetInt(data[ "type" ]);
                 newData.nameIds = data[ "nameIds" ];
                 actorDataList.ActorDataList.Add(newData);
             }
               
             if  (newFile) {
                 AssetDatabase.CreateAsset(actorDataList, FILE_PATH +  "ActorDataList.asset" );
             } else {
                 EditorUtility.SetDirty(actorDataList);
             }      
         }
         else  if  (xmlPath.Contains ( "ActorDataA.xml" )) {
             GActorDataList actorDataList =  null ;
               
             UnityEngine.Object oldFile = AssetDatabase.LoadAssetAtPath (xmlPath,  typeof (GActorDataList));
             bool  newFile =  false ;
             if  (oldFile) {
                 actorDataList = oldFile  as  GActorDataList;
             } else {
                 actorDataList =  new  GActorDataList();
                 newFile =  true ;
             }
             actorDataList.ActorDataList.Clear ();
               
             for  ( int  i = 0; i < rl.Count; i++) {
                 ActorData newData =  new  ActorData();
                 Row data = rl[i];
                 newData.id = data[ "id" ];
                 newData.type = GetInt(data[ "type" ]);
                 newData.nameIds = data[ "nameIds" ];
                 actorDataList.ActorDataList.Add(newData);
             }
               
             if  (newFile) {
                 AssetDatabase.CreateAsset(actorDataList, FILE_PATH +  "ActorDataListA.asset" );
             } else {
                 EditorUtility.SetDirty(actorDataList);
             }      
         }
         else  if  (xmlPath.Contains ( "ActorDataB.xml" )) {
             GActorDataList actorDataList =  null ;
               
             UnityEngine.Object oldFile = AssetDatabase.LoadAssetAtPath (xmlPath,  typeof (GActorDataList));
             bool  newFile =  false ;
             if  (oldFile) {
                 actorDataList = oldFile  as  GActorDataList;
             } else {
                 actorDataList =  new  GActorDataList();
                 newFile =  true ;
             }
             actorDataList.ActorDataList.Clear ();
               
             for  ( int  i = 0; i < rl.Count; i++) {
                 ActorData newData =  new  ActorData();
                 Row data = rl[i];
                 newData.id = data[ "id" ];
                 newData.type = GetInt(data[ "type" ]);
                 newData.nameIds = data[ "nameIds" ];
                 actorDataList.ActorDataList.Add(newData);
             }
               
             if  (newFile) {
                 AssetDatabase.CreateAsset(actorDataList, FILE_PATH +  "ActorDataListB.asset" );
             } else {
                 EditorUtility.SetDirty(actorDataList);
             }      
         }
     }
   
     static  int  GetInt ( string  data)
     {
         float  val = 0;
         try  {
             val =  float .Parse (data);
         catch  (Exception e) {
             Debug.LogError (e.Message +  "  data["  + data +  "]" );
         }
         return  Mathf.RoundToInt (val); 
     }
       
     static  float  GetFloat ( string  data)
     {
         float  val = 0;
         try  {
             val =  float .Parse (data);
         catch  (Exception e) {
             Debug.LogError (e.Message +  "  data["  + data +  "]" );
         }
         return  val;
     }
       
     static  bool  GetBool ( string  data)
     {
         int  val = 0;
         try  {
             val =  int .Parse (data);
         catch  (Exception e) {
             Debug.LogError (e.Message +  "  data["  + data +  "]" );
         }
         return  val == 0 ?  false  true ;
     }
}
   
/** xmlsheel所有字符串数据 */
public  class  xmlSheetList{
     public  List< string > sheetList =  new  List< string > ();
   
     public  void  Add( string  str)
     {
         sheetList.Add (str);
     }
   
     public  void  Clear(){
         sheetList.Clear();
     }
}
   
/** xml (key, Value) Cell */
public  class  Row
{
     public  List< string > _cells=  new  List< string >();
     public  List< string > _key =  new  List< string >();
       
     public  string  this [ string  key]
     {
         get {
             string  val =  "" ;
             int  pos = _key.IndexOf(key);
             if (pos < 0 || pos >= _cells.Count)
             {
                 Debug.LogError( "can't find the value of the key:[" +key+ "]" );
             } else {
                 val = _cells[pos]; 
             }
             return  val;
         }
     }
}
上面代码主要是读取和解析excel 
GActorDataList 是自己定义的数据格式,根据自己需求自己定义 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using  UnityEngine;
using  System.Collections;
using  System.Collections.Generic;
   
[System.Serializable]
public  class  ActorData{
     public  string  id;
     public  int  type;
     public  string  nameIds;
}
   
public  class  GActorDataList : ScriptableObject {
     public  List<ActorData> ActorDataList =  new  List<ActorData> ();
}
这就是全部的代码和思路,如果哪里写的不好欢迎吐槽!如果看着凑合或者有更好的解决方案的更是欢迎吐槽!

转载:http://game.ceeger.com/forum/read.php?tid=20617
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值