ExportLanguage.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. using UnityEditor;
  2. using UnityEngine;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using Excel;
  7. using System.Data;
  8. using System.Xml;
  9. using System.Threading;
  10. public class ExportLanguage : EditorWindow
  11. {
  12. [MenuItem("QHJ/Design Tools/Export Language")]
  13. public static void AddWindow()
  14. {
  15. ExportLanguage window = (ExportLanguage)EditorWindow.GetWindow(typeof(ExportLanguage), false, "Export Language");
  16. window.Show();
  17. }
  18. public List<string> nameArray = new List<string>();
  19. private string defaultPath;
  20. private bool shouldDelete = true;
  21. private bool isSuccess;
  22. private string text;
  23. private Dictionary<string, XmlNode> parentNodeDict;
  24. private string lijiaUrl = "192.168.1.50";
  25. private string localUrl = "192.168.1.41";
  26. private string remoteUrl = "218.244.129.189";
  27. private bool toLijia = false;
  28. private bool toLocal = false;
  29. private bool toRemote = false;
  30. private string sourcePath = "";
  31. void Awake()
  32. {
  33. defaultPath = Application.dataPath + @"/XlsxSource";
  34. if (!Directory.Exists(defaultPath))
  35. Directory.CreateDirectory(defaultPath);
  36. GetObjectNameToArray<string>(defaultPath, "xlsx");
  37. }
  38. void OnGUI()
  39. {
  40. GUILayout.Label(new GUIContent("1、导出所有语言文件到language目录"));
  41. shouldDelete = GUILayout.Toggle(shouldDelete, new GUIContent("覆盖已有文件"));
  42. if (GUILayout.Button("立即导出", GUILayout.Height(30)))
  43. CreateAllXml();
  44. GUILayout.Space(10);
  45. GUILayout.Label(new GUIContent("2、生成并上传服务器用语言文件"));
  46. if (GUILayout.Button("生成服务器语言文件", GUILayout.Height(30)))
  47. CreateAllPhp();
  48. GUILayout.Space(10);
  49. GUILayout.Label("选择要上传语言配置的服务器,可多选", GUILayout.Height(20));
  50. toLijia = GUILayout.Toggle(toLijia, "上传到李嘉服务器");
  51. toLocal = GUILayout.Toggle(toLocal, "上传到内网服务器");
  52. GUILayout.BeginHorizontal();
  53. toRemote = GUILayout.Toggle(toRemote, "上传到外网服务器");
  54. GUILayout.ExpandWidth(false);
  55. GUILayout.Label("[url]" + remoteUrl);
  56. GUILayout.EndHorizontal();
  57. GUILayout.BeginHorizontal();
  58. if (GUILayout.Button("全选", GUILayout.Width(40), GUILayout.Height(20)))
  59. {
  60. toLijia = true;
  61. toLocal = true;
  62. toRemote = true;
  63. }
  64. if (GUILayout.Button("清空", GUILayout.Width(40), GUILayout.Height(20)))
  65. {
  66. toLijia = false;
  67. toLocal = false;
  68. toRemote = false;
  69. }
  70. GUILayout.EndHorizontal();
  71. if (GUILayout.Button("上传配置到服务器", GUILayout.Height(30)))
  72. {
  73. sourcePath = Application.dataPath + @"/XlsxSource";
  74. Dictionary<string, LanguageUploadData> data = new Dictionary<string, LanguageUploadData>();
  75. if (toLijia)
  76. {
  77. LanguageUploadData data0 = new LanguageUploadData();
  78. data0.targetUrl = lijiaUrl;
  79. data0.sourcePath = sourcePath;
  80. if (!data.ContainsKey(lijiaUrl))
  81. data.Add(lijiaUrl, data0);
  82. }
  83. if (toLocal)
  84. {
  85. LanguageUploadData data1 = new LanguageUploadData();
  86. data1.targetUrl = localUrl;
  87. data1.sourcePath = sourcePath;
  88. if (!data.ContainsKey(localUrl))
  89. data.Add(localUrl, data1);
  90. }
  91. if (toRemote)
  92. {
  93. LanguageUploadData data2 = new LanguageUploadData();
  94. data2.targetUrl = remoteUrl;
  95. data2.sourcePath = sourcePath;
  96. if (!data.ContainsKey(remoteUrl))
  97. data.Add(remoteUrl, data2);
  98. }
  99. if (!toLijia && !toLocal && !toRemote)
  100. ShowNotification(new GUIContent("请至少选择一个上传地址"));
  101. new LanguageUploadFiles(data);
  102. }
  103. }
  104. /// <summary>
  105. /// Return all files' name in target path in Assets//
  106. /// </summary>
  107. /// <returns>File name in array</returns>
  108. /// <param name="path">Assets sublevel path</param>
  109. /// <param name="pattern">File type filter</param>
  110. /// <typeparam name="T">Class name</typeparam>
  111. void GetObjectNameToArray<T>(string path, string pattern, string subDirectory = "")
  112. {
  113. try
  114. {
  115. //return file name by array in target folder & subfolder, it can be null
  116. string[] files = Directory.GetFiles(path);
  117. for (int i = 0; i < files.Length; i++)
  118. {
  119. string p = files[i];
  120. //file
  121. int index = p.LastIndexOf("\\");
  122. string folder = p.Substring(0, index + 1);
  123. string fileName = p.Substring(index + 1);
  124. //if directoryEntries is not null, tempPaths cannot be null after splited
  125. if (fileName.EndsWith(".meta"))
  126. continue;
  127. string[] pathSplit = StringExtention.SplitWithString(fileName, ".");
  128. if (pathSplit.Length > 1 && pathSplit[0].Contains("language"))
  129. {
  130. nameArray.Add(subDirectory + "\\" + pathSplit[0]);
  131. }
  132. }
  133. //recursion
  134. string[] folders = Directory.GetDirectories(path);
  135. for (int i = 0; i < folders.Length; i++)
  136. {
  137. string p = folders[i];
  138. GetObjectNameToArray<T>(p, pattern, p.Substring(defaultPath.Length));
  139. }
  140. }
  141. catch (System.IO.DirectoryNotFoundException)
  142. {
  143. Debug.Log("The path encapsulated in the " + path + "Directory object does not exist.");
  144. }
  145. }
  146. /// <summary>
  147. /// custom split string function
  148. /// </summary>
  149. private class StringExtention
  150. {
  151. public static string[] SplitWithString(string sourceString, string splitString)
  152. {
  153. string tempSourceString = sourceString;
  154. List<string> arrayList = new List<string>();
  155. string s = string.Empty;
  156. while (sourceString.IndexOf(splitString) > -1) //split
  157. {
  158. s = sourceString.Substring(0, sourceString.IndexOf(splitString));
  159. sourceString = sourceString.Substring(sourceString.IndexOf(splitString) + splitString.Length);
  160. arrayList.Add(s);
  161. }
  162. arrayList.Add(sourceString);
  163. return arrayList.ToArray();
  164. }
  165. }
  166. private void CreateAllXml()
  167. {
  168. foreach (string str in nameArray)
  169. {
  170. if (!str.Contains("language"))
  171. continue;
  172. CreateXml(str);
  173. }
  174. if (isSuccess)
  175. {
  176. ShowNotification(new GUIContent( "已成功导出!"));
  177. DirectoryInfo di = new DirectoryInfo(defaultPath);
  178. DirectoryInfo[] diArr = di.GetDirectories();
  179. isSuccess = false;
  180. AssetDatabase.Refresh();
  181. }
  182. else
  183. ShowNotification(new GUIContent("文件有错误!"));
  184. }
  185. private void CreateXml(string fileName)
  186. {
  187. parentNodeDict = new Dictionary<string, XmlNode>();
  188. string realName = StringExtention.SplitWithString(fileName, "\\")[2];
  189. string filepath = Application.dataPath + @"/Resources/XML/Config/All/" + realName + ".xml";
  190. text = "";
  191. filepath = filepath.Replace("\\", "/");
  192. string[] pathArr = filepath.Split('/');
  193. string tempPath = "";
  194. for(int i = 0; i < pathArr.Length; i++)
  195. {
  196. tempPath += pathArr[i] + "/";
  197. if (i > 1 && i < pathArr.Length - 1)
  198. {
  199. if (!Directory.Exists(tempPath))
  200. {
  201. Directory.CreateDirectory(tempPath);
  202. }
  203. }
  204. }
  205. if ((!File.Exists(filepath) && !shouldDelete) || shouldDelete)
  206. {
  207. XmlDocument xmlDoc = new XmlDocument();
  208. tt(fileName, filepath, xmlDoc);
  209. //try
  210. //{
  211. // tt(fileName, filepath, xmlDoc);
  212. //}
  213. //catch (Exception e)
  214. //{
  215. // text += "Exception " + e.Message;
  216. // Debug.Log("Exception " + e.Message);
  217. //}
  218. }
  219. }
  220. private void tt(string fileName, string filepath, XmlDocument xmlDoc)
  221. {
  222. FileStream stream = File.Open(Application.dataPath + @"/XlsxSource" + fileName + ".xlsx", FileMode.Open, FileAccess.Read);
  223. IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
  224. text += "\nexcelReader.ResultsCount is" + excelReader.ResultsCount + "\n";
  225. text += "start excelReader. \n";
  226. DataSet result = excelReader.AsDataSet();
  227. text += "get result successful? result[" + result + "]";
  228. text += "result columns count is " + result.Tables[0].Columns.Count;
  229. int columns = result.Tables[0].Columns.Count;
  230. int rows = result.Tables[0].Rows.Count;
  231. //start create xml
  232. XmlElement root = xmlDoc.CreateElement("lan");
  233. XmlNode currentChildNode = null;
  234. string parentNodeName = "";
  235. for (int i = 0; i < rows; i++)
  236. {
  237. if (i == 0)
  238. {
  239. continue;
  240. }
  241. for (int j = 0; j < columns; j++)
  242. {
  243. string nvalue = result.Tables[0].Rows[i][j].ToString();
  244. if (i > 2)
  245. {
  246. switch (j)
  247. {
  248. case 0:
  249. if (!parentNodeDict.ContainsKey(nvalue))
  250. {
  251. if (nvalue == "")
  252. {
  253. Debug.LogError("第" + (i + 1) + "行有错误" + "\nxmlDoc" + xmlDoc + "\n" + nvalue + "ij" + i + " " + j);
  254. break;
  255. }
  256. XmlNode node = xmlDoc.CreateElement(nvalue);
  257. parentNodeDict.Add(nvalue, node);
  258. }
  259. parentNodeName = nvalue;
  260. break;
  261. case 1:
  262. if (nvalue == "")
  263. {
  264. Debug.LogError("第"+(i+1)+"行有错误"+"\nxmlDoc" + xmlDoc + "\n" + nvalue + "ij" + i + " " + j);
  265. break;
  266. }
  267. currentChildNode = xmlDoc.CreateElement(nvalue);
  268. parentNodeDict[parentNodeName].AppendChild(currentChildNode);
  269. break;
  270. case 2:
  271. XmlCDataSection cData = xmlDoc.CreateCDataSection(nvalue);
  272. currentChildNode.AppendChild(cData);
  273. break;
  274. case 3:
  275. XmlAttribute comment = xmlDoc.CreateAttribute("comm");
  276. comment.Value = nvalue;
  277. currentChildNode.Attributes.Append(comment);
  278. break;
  279. }
  280. //Debug.Log("labels[j] is " + labels[j] + ", nvalue is " + nvalue);
  281. }
  282. //Debug.Log(nvalue);
  283. }
  284. }
  285. foreach (KeyValuePair<string, XmlNode> keyValue in parentNodeDict)
  286. root.AppendChild(keyValue.Value);
  287. xmlDoc.AppendChild(root);
  288. xmlDoc.Save(filepath);
  289. AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
  290. // AssetDatabase.ImportAsset(@"Assets/Resources/XML/Config" + fileName + ".xml", ImportAssetOptions.ForceUpdate);
  291. //Debug.Log(fileName + ".xml is saved to " + filepath + ", count is " + idArr.Count);
  292. isSuccess = true;
  293. }
  294. private void CreateAllPhp()
  295. {
  296. foreach (string str in nameArray)
  297. {
  298. if (!str.Contains("language"))
  299. continue;
  300. CreatePhp(str);
  301. }
  302. if (isSuccess)
  303. {
  304. ShowNotification(new GUIContent("已成功导出!"));
  305. DirectoryInfo di = new DirectoryInfo(defaultPath);
  306. DirectoryInfo[] diArr = di.GetDirectories();
  307. isSuccess = false;
  308. }
  309. else
  310. ShowNotification(new GUIContent("文件有错误!"));
  311. }
  312. private void CreatePhp(string fileName)
  313. {
  314. string realName = StringExtention.SplitWithString(fileName, "\\")[1];
  315. string filepath = defaultPath + "/" + realName + ".php";
  316. text = "";
  317. filepath = filepath.Replace("\\", "/");
  318. string[] pathArr = filepath.Split('/');
  319. string tempPath = "";
  320. for (int i = 0; i < pathArr.Length; i++)
  321. {
  322. tempPath += pathArr[i] + "/";
  323. if (i > 1 && i < pathArr.Length - 1)
  324. {
  325. if (!Directory.Exists(tempPath))
  326. {
  327. Directory.CreateDirectory(tempPath);
  328. }
  329. }
  330. }
  331. if ((!File.Exists(filepath) && !shouldDelete) || shouldDelete)
  332. {
  333. try
  334. {
  335. string fullText = "<?php\n";
  336. FileStream stream = File.Open(Application.dataPath + @"/XlsxSource" + fileName + ".xlsx", FileMode.Open, FileAccess.Read);
  337. IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
  338. text += "\nexcelReader.ResultsCount is" + excelReader.ResultsCount + "\n";
  339. text += "start excelReader. \n";
  340. DataSet result = excelReader.AsDataSet();
  341. text += "get result successful? result[" + result + "]";
  342. text += "result columns count is " + result.Tables[0].Columns.Count;
  343. int columns = result.Tables[0].Columns.Count;
  344. int rows = result.Tables[0].Rows.Count;
  345. //start create xml
  346. for (int i = 0; i < rows; i++)
  347. {
  348. if (i == 0)
  349. {
  350. continue;
  351. }
  352. for (int j = 0; j < columns; j++)
  353. {
  354. string nvalue = result.Tables[0].Rows[i][j].ToString();
  355. if (i > 2)
  356. {
  357. switch (j)
  358. {
  359. case 0:
  360. fullText += "$LANG['" + nvalue + "|";
  361. break;
  362. case 1:
  363. fullText += nvalue + "'] = '";
  364. break;
  365. case 2:
  366. nvalue = nvalue.Replace("\'", "\\\'");
  367. fullText += nvalue + "\';\n";
  368. break;
  369. }
  370. }
  371. }
  372. }
  373. fullText += "?>";
  374. StreamWriter sw = new StreamWriter(filepath);
  375. string w = fullText;
  376. sw.Write(w);
  377. sw.Close();
  378. AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
  379. isSuccess = true;
  380. }
  381. catch (Exception e)
  382. {
  383. text += "Exception " + e.Message;
  384. Debug.Log("Exception " + e.Message);
  385. }
  386. }
  387. }
  388. private void HideNotification()
  389. {
  390. this.RemoveNotification();
  391. }
  392. void OnInspectorUpdate()
  393. {
  394. this.Repaint();
  395. }
  396. void OnDestroy()
  397. {
  398. EditorUtility.UnloadUnusedAssetsImmediate();
  399. }
  400. }
  401. public class LanguageUploadData
  402. {
  403. public string sourcePath;
  404. public string targetUrl;
  405. public string GetCmd()
  406. {
  407. string command = "@echo off\r\n" +
  408. "echo open " + targetUrl + ">ftp.up\r\n" +
  409. "echo gaoyuqin>>ftp.up\r\n" +
  410. "echo Gaoyuqin123654>>ftp.up\r\n" +
  411. //"echo Cd .\\User >>ftp.up\r\n" +
  412. "echo binary>>ftp.up\r\n" +
  413. "echo lcd \"" + sourcePath + "\">>ftp.up\r\n" +
  414. "echo prompt>>ftp.up\r\n" +
  415. "echo mkdir qwsk/lang/>>ftp.up\r\n" +
  416. "echo cd qwsk/lang/>>ftp.up\r\n" +
  417. "echo mput *.php>>ftp.up\r\n" +
  418. "echo bye>>ftp.up\r\n" +
  419. "FTP -s:ftp.up\r\n" +
  420. "del ftp.up /q\r\n" +
  421. "pause\r\n";
  422. return command;
  423. }
  424. }
  425. public class LanguageUploadFiles
  426. {
  427. private Dictionary<string, LanguageUploadData> data;
  428. private Thread s;
  429. public LanguageUploadFiles(Dictionary<string, LanguageUploadData> data)
  430. {
  431. this.data = data;
  432. s = new Thread(Run);
  433. s.Start();
  434. }
  435. private void Run()
  436. {
  437. foreach (string key in data.Keys)
  438. {
  439. LanguageUploadData uploadData = data[key];
  440. RunCmd(key, uploadData.GetCmd());
  441. Debug.Log("【RunCmd】" + uploadData.sourcePath + " upload to---- 【 " + uploadData.targetUrl + " 】");
  442. }
  443. s.Abort();
  444. }
  445. private void RunCmd(string key, string command)
  446. {
  447. Debug.Log(command);
  448. File.WriteAllText(key + "-upload-language.bat", command, System.Text.Encoding.GetEncoding(936));
  449. System.Diagnostics.Process.Start(key + "-upload-language.bat");
  450. }
  451. }