MainForm.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. using FastColoredTextBoxNS;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. namespace excel2json.GUI
  9. {
  10. /// <summary>
  11. /// 主窗口
  12. /// </summary>
  13. public partial class MainForm : Form
  14. {
  15. // Excel导入数据管理
  16. private DataManager mDataMgr;
  17. private string mCurrentXlsx;
  18. // 支持语法高亮的文本框
  19. private FastColoredTextBox mJsonTextBox;
  20. private FastColoredTextBox mCSharpTextBox;
  21. private FastColoredTextBox mLuaTextBox;
  22. // 文本框的样式
  23. private TextStyle mBrownStyle = new TextStyle(Brushes.Brown, null, FontStyle.Regular);
  24. private TextStyle mMagentaStyle = new TextStyle(Brushes.Magenta, null, FontStyle.Regular);
  25. private TextStyle mGreenStyle = new TextStyle(Brushes.Green, null, FontStyle.Regular);
  26. // 导出数据相关的按钮,方便整体Enable/Disable
  27. private List<ToolStripButton> mExportButtonList;
  28. // 打开的excel文件名,不包含后缀xlsx。。。
  29. private String FileName;
  30. /// <summary>
  31. /// 构造函数,初始化控件初值;创建文本框
  32. /// </summary>
  33. public MainForm()
  34. {
  35. InitializeComponent();
  36. //-- syntax highlight text box
  37. mJsonTextBox = createTextBoxInTab(this.tabPageJSON);
  38. mJsonTextBox.Language = Language.Custom;
  39. mJsonTextBox.TextChanged += new EventHandler<TextChangedEventArgs>(this.jsonTextChanged);
  40. mCSharpTextBox = createTextBoxInTab(this.tabCSharp);
  41. mCSharpTextBox.Language = Language.CSharp;
  42. mLuaTextBox = createTextBoxInTab(this.tabPageLua);
  43. mCSharpTextBox.Language = Language.Lua;
  44. //-- componet init states
  45. this.comboBoxType.SelectedIndex = 0;
  46. this.comboBoxLowcase.SelectedIndex = 1;
  47. this.comboBoxHeader.SelectedIndex = 1;
  48. this.comboBoxDateFormat.SelectedIndex = 0;
  49. this.comboBoxSheetName.SelectedIndex = 1;
  50. this.comboBoxEncoding.Items.Clear();
  51. this.comboBoxEncoding.Items.Add("utf8-nobom");
  52. foreach (EncodingInfo ei in Encoding.GetEncodings())
  53. {
  54. Encoding e = ei.GetEncoding();
  55. this.comboBoxEncoding.Items.Add(e.HeaderName);
  56. }
  57. this.comboBoxEncoding.SelectedIndex = 0;
  58. //-- button list
  59. mExportButtonList = new List<ToolStripButton>();
  60. mExportButtonList.Add(this.btnCopyJSON);
  61. mExportButtonList.Add(this.btnSaveJson);
  62. mExportButtonList.Add(this.btnCopyCSharp);
  63. mExportButtonList.Add(this.btnSaveCSharp);
  64. mExportButtonList.Add(this.btnSaveLua);
  65. enableExportButtons(false);
  66. //-- data manager
  67. mDataMgr = new DataManager();
  68. this.btnReimport.Enabled = false;
  69. }
  70. /// <summary>
  71. /// 设置导出相关的按钮是否可用
  72. /// </summary>
  73. /// <param name="enable">是否可用</param>
  74. private void enableExportButtons(bool enable)
  75. {
  76. foreach (var btn in mExportButtonList)
  77. btn.Enabled = enable;
  78. }
  79. /// <summary>
  80. /// 在一个TabPage中创建Text Box
  81. /// </summary>
  82. /// <param name="tab">TabPage容器控件</param>
  83. /// <returns>新建的Text Box控件</returns>
  84. private FastColoredTextBox createTextBoxInTab(TabPage tab)
  85. {
  86. FastColoredTextBox textBox = new FastColoredTextBox();
  87. textBox.Dock = DockStyle.Fill;
  88. textBox.Font = new Font("Microsoft YaHei", 11F);
  89. tab.Controls.Add(textBox);
  90. return textBox;
  91. }
  92. /// <summary>
  93. /// 设置Json文本高亮格式
  94. /// </summary>
  95. private void jsonTextChanged(object sender, TextChangedEventArgs e)
  96. {
  97. e.ChangedRange.ClearStyle(mBrownStyle, mMagentaStyle, mGreenStyle);
  98. //allow to collapse brackets block
  99. e.ChangedRange.SetFoldingMarkers("{", "}");
  100. //string highlighting
  101. e.ChangedRange.SetStyle(mBrownStyle, @"""""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'");
  102. //number highlighting
  103. e.ChangedRange.SetStyle(mGreenStyle, @"\b\d+[\.]?\d*([eE]\-?\d+)?[lLdDfF]?\b|\b0x[a-fA-F\d]+\b");
  104. }
  105. /// <summary>
  106. /// 使用BackgroundWorker加载Excel文件,使用UI中的Options设置
  107. /// </summary>
  108. /// <param name="path">Excel文件路径</param>
  109. private void loadExcelAsync(string path)
  110. {
  111. mCurrentXlsx = path;
  112. FileName = System.IO.Path.GetFileNameWithoutExtension(path);
  113. //-- update ui
  114. this.btnReimport.Enabled = true;
  115. this.labelExcelFile.Text = path;
  116. enableExportButtons(false);
  117. this.statusLabel.IsLink = false;
  118. this.statusLabel.Text = "Loading Excel ...";
  119. //-- load options from ui
  120. Program.Options options = new Program.Options();
  121. options.ExcelPath = path;
  122. options.ExportArray = this.comboBoxType.SelectedIndex == 0;
  123. options.Encoding = this.comboBoxEncoding.SelectedText;
  124. options.Lowcase = this.comboBoxLowcase.SelectedIndex == 0;
  125. options.HeaderRows = int.Parse(this.comboBoxHeader.Text);
  126. options.DateFormat = this.comboBoxDateFormat.Text;
  127. options.ForceSheetName = this.comboBoxSheetName.SelectedIndex == 0;
  128. options.ExcludePrefix = this.textBoxExculdePrefix.Text;
  129. options.CellJson = this.checkBoxCellJson.Checked;
  130. //-- start import
  131. this.backgroundWorker.RunWorkerAsync(options);
  132. }
  133. /// <summary>
  134. /// 接受Excel拖放事件
  135. /// </summary>
  136. private void panelExcelDropBox_DragDrop(object sender, DragEventArgs e)
  137. {
  138. string[] dropData = (string[])e.Data.GetData(DataFormats.FileDrop, false);
  139. if (dropData != null)
  140. {
  141. this.loadExcelAsync(dropData[0]);
  142. }
  143. }
  144. /// <summary>
  145. /// 显示Help文档
  146. /// </summary>
  147. private void btnHelp_Click(object sender, EventArgs e)
  148. {
  149. }
  150. /// <summary>
  151. /// 判断拖放对象是否是一个.xlsx文件
  152. /// </summary>
  153. private void panelExcelDropBox_DragEnter(object sender, DragEventArgs e)
  154. {
  155. if (e.Data.GetDataPresent(DataFormats.FileDrop))
  156. {
  157. string[] dropData = (string[])e.Data.GetData(DataFormats.FileDrop, false);
  158. if (dropData != null && dropData.Length > 0)
  159. {
  160. string szPath = dropData[0];
  161. string szExt = System.IO.Path.GetExtension(szPath);
  162. FileName = System.IO.Path.GetFileNameWithoutExtension(szPath);
  163. szExt = szExt.ToLower();
  164. if (szExt == ".xlsx")
  165. {
  166. e.Effect = DragDropEffects.All;
  167. return;
  168. }
  169. }
  170. }//end of if(file)
  171. e.Effect = DragDropEffects.None;
  172. }
  173. /// <summary>
  174. /// 执行实际的Excel加载
  175. /// </summary>
  176. private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  177. {
  178. lock (this.mDataMgr)
  179. {
  180. this.mDataMgr.loadExcel((Program.Options)e.Argument);
  181. }
  182. }
  183. /// <summary>
  184. /// Excel加载完成
  185. /// </summary>
  186. private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  187. {
  188. // 判断错误信息
  189. if (e.Error != null)
  190. {
  191. showStatus(e.Error.Message, Color.Red);
  192. return;
  193. }
  194. // 更新UI
  195. lock (this.mDataMgr)
  196. {
  197. this.statusLabel.IsLink = false;
  198. this.statusLabel.Text = "Load completed.";
  199. mJsonTextBox.Text = mDataMgr.JsonContext;
  200. mCSharpTextBox.Text = mDataMgr.CSharpCode;
  201. mLuaTextBox.Text = mDataMgr.LuaCode;
  202. enableExportButtons(true);
  203. }
  204. }
  205. /// <summary>
  206. /// 工具栏按钮:Import Excel
  207. /// </summary>
  208. private void btnImportExcel_Click(object sender, EventArgs e)
  209. {
  210. OpenFileDialog dlg = new OpenFileDialog();
  211. dlg.RestoreDirectory = true;
  212. dlg.Filter = "Excel File(*.xlsx)|*.xlsx";
  213. if (dlg.ShowDialog() == DialogResult.OK)
  214. {
  215. this.loadExcelAsync(dlg.FileName);
  216. }
  217. }
  218. /// <summary>
  219. /// 点击状态栏链接
  220. /// </summary>
  221. private void statusLabel_Click(object sender, EventArgs e)
  222. {
  223. if (this.statusLabel.IsLink)
  224. {
  225. System.Diagnostics.Process.Start(this.statusLabel.Text);
  226. }
  227. }
  228. /// <summary>
  229. /// 保存导出文件
  230. /// </summary>
  231. private void saveToFile(int type, string filter,string exFileName = "")
  232. {
  233. try
  234. {
  235. SaveFileDialog dlg = new SaveFileDialog();
  236. dlg.RestoreDirectory = true;
  237. dlg.Filter = filter;
  238. dlg.FileName = FileName + exFileName;
  239. if (dlg.ShowDialog() == DialogResult.OK)
  240. {
  241. lock (mDataMgr)
  242. {
  243. switch (type)
  244. {
  245. case 1:
  246. mDataMgr.saveJson(dlg.FileName);
  247. break;
  248. case 2:
  249. mDataMgr.saveCSharp(dlg.FileName);
  250. break;
  251. case 3:
  252. mDataMgr.saveLua(dlg.FileName);
  253. break;
  254. }
  255. }
  256. showStatus(string.Format("{0} saved!", dlg.FileName), Color.Black);
  257. }// end of if
  258. }
  259. catch (Exception ex)
  260. {
  261. showStatus(ex.Message, Color.Red);
  262. }
  263. }
  264. /// <summary>
  265. /// 工具栏按钮:Save Json
  266. /// </summary>
  267. private void btnSaveJson_Click(object sender, EventArgs e)
  268. {
  269. saveToFile(1, "Json File(*.json)|*.json");
  270. }
  271. /// <summary>
  272. /// 工具栏按钮:Copy Json
  273. /// </summary>
  274. private void btnCopyJSON_Click(object sender, EventArgs e)
  275. {
  276. lock (mDataMgr)
  277. {
  278. Clipboard.SetText(mDataMgr.JsonContext);
  279. showStatus("Json text copyed to clipboard.", Color.Black);
  280. }
  281. }
  282. /// <summary>
  283. /// 设置状态栏信息
  284. /// </summary>
  285. /// <param name="szMessage">信息文字</param>
  286. /// <param name="color">信息颜色</param>
  287. private void showStatus(string szMessage, Color color)
  288. {
  289. this.statusLabel.Text = szMessage;
  290. this.statusLabel.ForeColor = color;
  291. this.statusLabel.IsLink = false;
  292. }
  293. /// <summary>
  294. /// 配置项变更之后,手动重新导入xlsx文件
  295. /// </summary>
  296. private void btnReimport_Click(object sender, EventArgs e)
  297. {
  298. if (!string.IsNullOrEmpty(mCurrentXlsx))
  299. {
  300. loadExcelAsync(mCurrentXlsx);
  301. }
  302. }
  303. private void btnCopyCSharp_Click(object sender, EventArgs e)
  304. {
  305. lock (mDataMgr)
  306. {
  307. Clipboard.SetText(mDataMgr.CSharpCode);
  308. showStatus("C# code copyed to clipboard.", Color.Black);
  309. }
  310. }
  311. private void btnSaveCSharp_Click(object sender, EventArgs e)
  312. {
  313. saveToFile(2, "C# code file(*.cs)|*.cs");
  314. }
  315. private void btnSaveLua_Click(object sender, EventArgs e)
  316. {
  317. saveToFile(3, "Lua code file(*.lua)|*.lua","_key");
  318. }
  319. }
  320. }