├── .gitattributes
├── .gitignore
├── README.md
├── bin.zip
├── bin
├── ICSharpCode.SharpZipLib.dll
├── NPOI.OOXML.dll
├── NPOI.OpenXml4Net.dll
├── NPOI.OpenXmlFormats.dll
├── NPOI.dll
├── Newtonsoft.Json.dll
└── tablegen2.exe
├── doc
├── image1.png
├── image2.png
└── image3.png
├── tablegen2.sln
└── tablegen2
├── App.config
├── App.xaml
├── App.xaml.cs
├── ApplicationEvents.cs
├── BoolToVisibilityConverter.cs
├── CommandHelper.cs
├── MainWindow.xaml
├── MainWindow.xaml.cs
├── Program.cs
├── Properties
├── AssemblyInfo.cs
├── Resources.Designer.cs
├── Resources.resx
├── Settings.Designer.cs
└── Settings.settings
├── StaticResources.xaml
├── app.ico
├── common
├── AppData.cs
├── BinaryExtension.cs
├── FrameworkExtension.cs
├── GzipHelper.cs
├── JsonConfig.cs
├── Log.cs
├── MessageBoxExtensions.cs
└── Util.cs
├── layouts
├── common
│ ├── ButtonDark.xaml
│ ├── ButtonDark.xaml.cs
│ ├── ButtonLight.xaml
│ ├── ButtonLight.xaml.cs
│ ├── HelperPanel.xaml
│ ├── HelperPanel.xaml.cs
│ ├── ListItemBase.cs
│ ├── PopupWindow.xaml
│ ├── PopupWindow.xaml.cs
│ ├── WaitingControl.xaml
│ └── WaitingControl.xaml.cs
├── framework
│ ├── FrameConsole.xaml
│ ├── FrameConsole.xaml.cs
│ ├── FrameExcelView.xaml
│ ├── FrameExcelView.xaml.cs
│ ├── FrameFileTree.xaml
│ ├── FrameFileTree.xaml.cs
│ ├── FrameSetting.xaml
│ ├── FrameSetting.xaml.cs
│ ├── FrameSettingMore.xaml
│ ├── FrameSettingMore.xaml.cs
│ ├── FrameToolBar.xaml
│ ├── FrameToolBar.xaml.cs
│ ├── TreeListItem.xaml
│ ├── TreeListItem.xaml.cs
│ ├── TreeListView.xaml
│ └── TreeListView.xaml.cs
└── header
│ ├── HeaderFieldEdit.xaml
│ ├── HeaderFieldEdit.xaml.cs
│ ├── HeaderListItem.xaml
│ ├── HeaderListItem.xaml.cs
│ ├── HeaderListView.xaml
│ ├── HeaderListView.xaml.cs
│ ├── HeaderPage.xaml
│ └── HeaderPage.xaml.cs
├── logic
└── parser
│ ├── TableExcelData.cs
│ ├── TableExcelExportDat.cs
│ ├── TableExcelExportJson.cs
│ ├── TableExcelExportLua.cs
│ ├── TableExcelExportXml.cs
│ ├── TableExcelHeader.cs
│ ├── TableExcelImportDat.cs
│ ├── TableExcelReader.cs
│ ├── TableExcelRow.cs
│ ├── TableExcelWriter.cs
│ ├── TableExportFormat.cs
│ └── TableGenConfig.cs
├── packages
├── ICSharpCode.SharpZipLib.dll
├── NPOI.OOXML.dll
├── NPOI.OpenXml4Net.dll
├── NPOI.OpenXmlFormats.dll
├── NPOI.XML
├── NPOI.dll
├── Newtonsoft.Json.dll
└── Newtonsoft.Json.xml
├── res
└── excel.png
└── tablegen2.csproj
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | [Xx]64/
19 | [Xx]86/
20 | [Bb]uild/
21 | bld/
22 | [Bb]in/
23 | [Oo]bj/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 |
85 | # Visual Studio profiler
86 | *.psess
87 | *.vsp
88 | *.vspx
89 | *.sap
90 |
91 | # TFS 2012 Local Workspace
92 | $tf/
93 |
94 | # Guidance Automation Toolkit
95 | *.gpState
96 |
97 | # ReSharper is a .NET coding add-in
98 | _ReSharper*/
99 | *.[Rr]e[Ss]harper
100 | *.DotSettings.user
101 |
102 | # JustCode is a .NET coding add-in
103 | .JustCode
104 |
105 | # TeamCity is a build add-in
106 | _TeamCity*
107 |
108 | # DotCover is a Code Coverage Tool
109 | *.dotCover
110 |
111 | # NCrunch
112 | _NCrunch_*
113 | .*crunch*.local.xml
114 | nCrunchTemp_*
115 |
116 | # MightyMoose
117 | *.mm.*
118 | AutoTest.Net/
119 |
120 | # Web workbench (sass)
121 | .sass-cache/
122 |
123 | # Installshield output folder
124 | [Ee]xpress/
125 |
126 | # DocProject is a documentation generator add-in
127 | DocProject/buildhelp/
128 | DocProject/Help/*.HxT
129 | DocProject/Help/*.HxC
130 | DocProject/Help/*.hhc
131 | DocProject/Help/*.hhk
132 | DocProject/Help/*.hhp
133 | DocProject/Help/Html2
134 | DocProject/Help/html
135 |
136 | # Click-Once directory
137 | publish/
138 |
139 | # Publish Web Output
140 | *.[Pp]ublish.xml
141 | *.azurePubxml
142 |
143 | # TODO: Un-comment the next line if you do not want to checkin
144 | # your web deploy settings because they may include unencrypted
145 | # passwords
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # NuGet Packages
150 | *.nupkg
151 | # The packages folder can be ignored because of Package Restore
152 | **/packages/*
153 | # except build/, which is used as an MSBuild target.
154 | !**/packages/build/
155 | # Uncomment if necessary however generally it will be regenerated when needed
156 | #!**/packages/repositories.config
157 | # NuGet v3's project.json files produces more ignoreable files
158 | *.nuget.props
159 | *.nuget.targets
160 |
161 | # Microsoft Azure Build Output
162 | csx/
163 | *.build.csdef
164 |
165 | # Microsoft Azure Emulator
166 | ecf/
167 | rcf/
168 |
169 | # Windows Store app package directory
170 | AppPackages/
171 | BundleArtifacts/
172 |
173 | # Visual Studio cache files
174 | # files ending in .cache can be ignored
175 | *.[Cc]ache
176 | # but keep track of directories ending in .cache
177 | !*.[Cc]ache/
178 |
179 | # Others
180 | ClientBin/
181 | [Ss]tyle[Cc]op.*
182 | ~$*
183 | *~
184 | *.dbmdl
185 | *.dbproj.schemaview
186 | *.pfx
187 | *.publishsettings
188 | node_modules/
189 | orleans.codegen.cs
190 |
191 | # RIA/Silverlight projects
192 | Generated_Code/
193 |
194 | # Backup & report files from converting an old project file
195 | # to a newer Visual Studio version. Backup files are not needed,
196 | # because we have git ;-)
197 | _UpgradeReport_Files/
198 | Backup*/
199 | UpgradeLog*.XML
200 | UpgradeLog*.htm
201 |
202 | # SQL Server files
203 | *.mdf
204 | *.ldf
205 |
206 | # Business Intelligence projects
207 | *.rdl.data
208 | *.bim.layout
209 | *.bim_*.settings
210 |
211 | # Microsoft Fakes
212 | FakesAssemblies/
213 |
214 | # GhostDoc plugin setting file
215 | *.GhostDoc.xml
216 |
217 | # Node.js Tools for Visual Studio
218 | .ntvs_analysis.dat
219 |
220 | # Visual Studio 6 build log
221 | *.plg
222 |
223 | # Visual Studio 6 workspace options file
224 | *.opt
225 |
226 | # Visual Studio LightSwitch build output
227 | **/*.HTMLClient/GeneratedArtifacts
228 | **/*.DesktopClient/GeneratedArtifacts
229 | **/*.DesktopClient/ModelManifest.xml
230 | **/*.Server/GeneratedArtifacts
231 | **/*.Server/ModelManifest.xml
232 | _Pvt_Extensions
233 |
234 | # LightSwitch generated files
235 | GeneratedArtifacts/
236 | ModelManifest.xml
237 |
238 | # Paket dependency manager
239 | .paket/paket.exe
240 |
241 | # FAKE - F# Make
242 | .fake/
243 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 导表工具
2 | ======================
3 |
4 | 项目主页:https://github.com/monkey256/ExcelExport
5 |
6 | 
7 | 
8 | 
9 |
--------------------------------------------------------------------------------
/bin.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/bin.zip
--------------------------------------------------------------------------------
/bin/ICSharpCode.SharpZipLib.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/bin/ICSharpCode.SharpZipLib.dll
--------------------------------------------------------------------------------
/bin/NPOI.OOXML.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/bin/NPOI.OOXML.dll
--------------------------------------------------------------------------------
/bin/NPOI.OpenXml4Net.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/bin/NPOI.OpenXml4Net.dll
--------------------------------------------------------------------------------
/bin/NPOI.OpenXmlFormats.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/bin/NPOI.OpenXmlFormats.dll
--------------------------------------------------------------------------------
/bin/NPOI.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/bin/NPOI.dll
--------------------------------------------------------------------------------
/bin/Newtonsoft.Json.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/bin/Newtonsoft.Json.dll
--------------------------------------------------------------------------------
/bin/tablegen2.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/bin/tablegen2.exe
--------------------------------------------------------------------------------
/doc/image1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/doc/image1.png
--------------------------------------------------------------------------------
/doc/image2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/doc/image2.png
--------------------------------------------------------------------------------
/doc/image3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/doc/image3.png
--------------------------------------------------------------------------------
/tablegen2.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.25420.1
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "tablegen2", "tablegen2\tablegen2.csproj", "{4D5AEC09-00D5-41EA-9BE3-67D090C7FCC1}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {4D5AEC09-00D5-41EA-9BE3-67D090C7FCC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {4D5AEC09-00D5-41EA-9BE3-67D090C7FCC1}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {4D5AEC09-00D5-41EA-9BE3-67D090C7FCC1}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {4D5AEC09-00D5-41EA-9BE3-67D090C7FCC1}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/tablegen2/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/tablegen2/App.xaml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/tablegen2/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Configuration;
4 | using System.Data;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 | using System.Windows;
8 |
9 | namespace tablegen2
10 | {
11 | ///
12 | /// App.xaml 的交互逻辑
13 | ///
14 | public partial class App : Application
15 | {
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/tablegen2/ApplicationEvents.cs:
--------------------------------------------------------------------------------
1 | namespace tablegen2
2 | {
3 | static class ApplicationEvents
4 | {
5 | public static void Application_Startup()
6 | {
7 | AppData.loadConfig();
8 | }
9 |
10 | public static void Application_Exit()
11 | {
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/tablegen2/BoolToVisibilityConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Globalization;
3 | using System.Windows;
4 | using System.Windows.Data;
5 |
6 | namespace tablegen2
7 | {
8 | class BoolToVisibilityConverter : IValueConverter
9 | {
10 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
11 | {
12 | return (bool)value ? Visibility.Visible : Visibility.Hidden;
13 | }
14 |
15 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
16 | {
17 | throw new NotSupportedException();
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/tablegen2/CommandHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Text;
4 | using System.Windows;
5 | using tablegen2.logic;
6 | using tablegen2.layouts;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 |
10 | namespace tablegen2
11 | {
12 | internal enum CommandType
13 | {
14 | Unknown = 0,
15 | Help,
16 | OpenDatFile,
17 | OpenExcelFile,
18 | ExportFiles,
19 | }
20 |
21 | internal static class CommandHelper
22 | {
23 | //-h|-help|/h|/help
24 | //fullPath.exdat
25 | //fullPath.xls|.xlsx
26 | //-i excelFullPath|excelDir -o outputDir -t xml|json|lua|dat
27 |
28 | public static CommandType Command { get; internal set; }
29 |
30 | public static string OpenDatFullPath { get; internal set; }
31 |
32 | public static string OpenExcelFullPath { get; internal set; }
33 |
34 | public static string ExportInputPath { get; internal set; }
35 | public static string ExportOutputDir { get; internal set; }
36 | public static string ExportType { get; internal set; }
37 |
38 | static CommandHelper()
39 | {
40 | _analyzeCommandParameter();
41 | }
42 |
43 | public static void MsgBox(string str, params object[] args)
44 | {
45 | System.Windows.MessageBox.Show(
46 | string.Format(str, args),
47 | "提示",
48 | System.Windows.MessageBoxButton.OK,
49 | System.Windows.MessageBoxImage.Information);
50 | }
51 |
52 | private static void _analyzeCommandParameter()
53 | {
54 | Command = CommandType.Unknown;
55 |
56 | do
57 | {
58 | string[] arr = Environment.GetCommandLineArgs();
59 | if (arr.Length == 0)
60 | break;
61 |
62 | string[] cpy = arr;
63 | string s = arr[0];
64 | if (s.Contains("vshost") || s.ToLower() == Util.ModulePath.ToLower())
65 | {
66 | cpy = new string[arr.Length - 1];
67 | Array.Copy(arr, 1, cpy, 0, arr.Length - 1);
68 | }
69 |
70 | #region help
71 | if (cpy.Length == 1)
72 | {
73 | var c = cpy[0];
74 | if (c == "-h" || c == "-help" || c == "/h" || c == "/help")
75 | {
76 | Command = CommandType.Help;
77 | break;
78 | }
79 | }
80 | #endregion
81 |
82 | #region open dat
83 | if (cpy.Length == 1 && File.Exists(cpy[0]))
84 | {
85 | if (Path.GetExtension(cpy[0]).ToLower() == ".exdat")
86 | {
87 | Command = CommandType.OpenDatFile;
88 | OpenDatFullPath = cpy[0];
89 | break;
90 | }
91 | }
92 | #endregion
93 |
94 | #region open excel
95 | if (cpy.Length == 1 && File.Exists(cpy[0]))
96 | {
97 | var ext = Path.GetExtension(cpy[0]).ToLower();
98 | if (ext == ".xls" || ext == ".xlsx")
99 | {
100 | Command = CommandType.OpenExcelFile;
101 | OpenExcelFullPath = cpy[0];
102 | break;
103 | }
104 | }
105 | #endregion
106 |
107 | #region convert excel
108 | if (cpy.Length == 6)
109 | {
110 | var ps = new Dictionary();
111 | ps[cpy[0]] = cpy[1];
112 | ps[cpy[2]] = cpy[3];
113 | ps[cpy[4]] = cpy[5];
114 | var ks = ps.Keys.ToList();
115 | ks.Sort();
116 | if (string.Concat(ks) == "-i-o-t")
117 | {
118 | Command = CommandType.ExportFiles;
119 | ExportInputPath = ps["-i"];
120 | ExportOutputDir = ps["-o"];
121 | ExportType = ps["-t"];
122 | break;
123 | }
124 | }
125 | #endregion
126 | } while (false);
127 | }
128 |
129 | public static void processHelp()
130 | {
131 | var sb = new StringBuilder();
132 | sb.AppendLine("使用说明");
133 | sb.AppendLine("1.datPath");
134 | sb.AppendLine(" 功能说明:打开并查看.exdat文件");
135 | sb.AppendLine("2.excelPath");
136 | sb.AppendLine(" 功能说明:打开并查看.xls或.xlsx文件");
137 | sb.AppendLine("3.-i excelFullPath|excelDir -o outputDir -t xml|json|lua|dat");
138 | sb.AppendLine(" 功能说明:将Excel表或整个目录导出指定格式的数据文件");
139 | MsgBox(sb.ToString());
140 | }
141 |
142 | public static void processOpenDatFile()
143 | {
144 | try
145 | {
146 | var data = TableExcelImportDat.importFile(OpenDatFullPath);
147 | openEditUI(data, OpenDatFullPath);
148 | }
149 | catch (System.Exception ex)
150 | {
151 | MsgBox(ex.Message);
152 | }
153 | }
154 |
155 | public static void processOpenExcelFile()
156 | {
157 | try
158 | {
159 | var data = TableExcelReader.loadFromExcel(OpenExcelFullPath);
160 | openEditUI(data, OpenExcelFullPath);
161 | }
162 | catch (System.Exception ex)
163 | {
164 | MsgBox(ex.Message);
165 | }
166 | }
167 |
168 | private static void openEditUI(TableExcelData data, string fullPath)
169 | {
170 | var panel = new FrameExcelView();
171 | panel.refreshUIByTableExcelData(data);
172 | panel.setFilePath(fullPath);
173 |
174 | var pw = new PopupWindow(panel);
175 | pw.ResizeMode = ResizeMode.CanResize;
176 | pw.Title = string.Format("查看配置表 -- {0}", fullPath);
177 | pw.MinWidth = 600;
178 | pw.MinHeight = 400;
179 | pw.ShowInTaskbar = true;
180 | pw.WindowStartupLocation = WindowStartupLocation.CenterScreen;
181 |
182 | App app = new App();
183 | app.InitializeComponent();
184 | app.Run((Window)pw);
185 | }
186 |
187 | public static void processExportFiles()
188 | {
189 | var lst = new List();
190 | if (Directory.Exists(ExportInputPath))
191 | {
192 | lst = Directory.GetFiles(ExportInputPath, "*.xls", SearchOption.AllDirectories).ToList();
193 | lst.Union(Directory.GetFiles(ExportInputPath, "*.xlsx", SearchOption.AllDirectories));
194 | }
195 | else if (File.Exists(ExportInputPath))
196 | {
197 | lst.Add(ExportInputPath);
198 | }
199 | else
200 | {
201 | MsgBox("文件或目录不存在! {0}", ExportInputPath);
202 | return;
203 | }
204 |
205 | Util.MakesureFolderExist(ExportOutputDir);
206 | if (!Directory.Exists(ExportOutputDir))
207 | {
208 | MsgBox("无法创建目录! {0}", ExportOutputDir);
209 | return;
210 | }
211 |
212 | var fmt = TableExportFormat.Unknown;
213 | switch (ExportType.ToLower())
214 | {
215 | case "xml":
216 | fmt = TableExportFormat.Xml;
217 | break;
218 | case "json":
219 | fmt = TableExportFormat.Json;
220 | break;
221 | case "lua":
222 | fmt = TableExportFormat.Lua;
223 | break;
224 | case "dat":
225 | fmt = TableExportFormat.Dat;
226 | break;
227 | }
228 | if (fmt == TableExportFormat.Unknown)
229 | {
230 | MsgBox("无法识别的导出格式! {0}", ExportType);
231 | return;
232 | }
233 |
234 | foreach (var filePath in lst)
235 | {
236 | try
237 | {
238 | exportFile(filePath, ExportOutputDir, fmt);
239 | }
240 | catch (System.Exception ex)
241 | {
242 | MsgBox("转换文件'{0}'时出错:\n{1}", filePath, ex.Message);
243 | return;
244 | }
245 | }
246 | }
247 |
248 | private static void exportFile(string excelPath, string outputDir, TableExportFormat fmt)
249 | {
250 | var data = TableExcelReader.loadFromExcel(excelPath);
251 | switch (fmt)
252 | {
253 | case TableExportFormat.Dat:
254 | {
255 | var exportPath = Path.Combine(outputDir, string.Format("{0}.exdat", Path.GetFileNameWithoutExtension(excelPath)));
256 | TableExcelExportDat.exportExcelFile(data, exportPath);
257 | }
258 | break;
259 | case TableExportFormat.Json:
260 | {
261 | var exportPath = Path.Combine(outputDir, string.Format("{0}.json", Path.GetFileNameWithoutExtension(excelPath)));
262 | TableExcelExportJson.exportExcelFile(data, exportPath);
263 | }
264 | break;
265 | case TableExportFormat.Xml:
266 | {
267 | var exportPath = Path.Combine(outputDir, string.Format("{0}.xml", Path.GetFileNameWithoutExtension(excelPath)));
268 | TableExcelExportXml.exportExcelFile(data, exportPath);
269 | }
270 | break;
271 | case TableExportFormat.Lua:
272 | {
273 | var exportPath = Path.Combine(outputDir, string.Format("{0}.lua", Path.GetFileNameWithoutExtension(excelPath)));
274 | TableExcelExportLua.exportExcelFile(data, exportPath);
275 | }
276 | break;
277 | }
278 | }
279 | }
280 | }
281 |
--------------------------------------------------------------------------------
/tablegen2/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/tablegen2/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.IO;
3 | using System.Linq;
4 | using System.Windows;
5 | using System.Windows.Input;
6 | using System.Windows.Media;
7 | using tablegen2.layouts;
8 | using tablegen2.logic;
9 |
10 | namespace tablegen2
11 | {
12 | ///
13 | /// MainWindow.xaml 的交互逻辑
14 | ///
15 | public partial class MainWindow : Window
16 | {
17 | public MainWindow()
18 | {
19 | AppData.MainWindow = this;
20 |
21 | InitializeComponent();
22 |
23 | setting.ExcelDirChanged += () => tree.refreshExcelPath(AppData.Config.ExcelDir);
24 | setting.ExportFormatChanged += () => refreshButtonGenAll();
25 | setting.MoreSettingEvent += () => _flipMoreSettingPanel();
26 | tree.OpenExcelRequest += () => setting.browseExcelDirectory();
27 |
28 | if (AppData.Config != null)
29 | refreshButtonGenAll();
30 | }
31 |
32 | #region 事件处理
33 | private void Window_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
34 | {
35 | if (e.Key == Key.F1)
36 | {
37 | _flipHelpPanel();
38 | e.Handled = true;
39 | }
40 | }
41 |
42 | private void btnHelp_Clicked(object sender, RoutedEventArgs e)
43 | {
44 | _flipHelpPanel();
45 | }
46 |
47 | private void btnGenAll_Clicked(object sender, RoutedEventArgs e)
48 | {
49 | string excelDir = AppData.Config.ExcelDir;
50 | string exportDir = AppData.Config.ExportDir;
51 | TableExportFormat fmt = AppData.Config.ExportFormat;
52 |
53 | if (string.IsNullOrEmpty(excelDir) || !Directory.Exists(excelDir))
54 | {
55 | Log.Err("请选择合法的Excel配置目录!");
56 | return;
57 | }
58 |
59 | if (string.IsNullOrEmpty(exportDir) || !Directory.Exists(exportDir))
60 | {
61 | Log.Err("请选择合法的导出目录!");
62 | return;
63 | }
64 |
65 | if (fmt == TableExportFormat.Unknown)
66 | {
67 | Log.Err("请选择导出数据格式!");
68 | return;
69 | }
70 |
71 | var excels = tree.AllExcels.ToList();
72 | if (excels.Count == 0)
73 | {
74 | Log.Wrn("您选择的配置目录中不包含任何Excel文件! 目录:{0}", excelDir);
75 | return;
76 | }
77 |
78 | Log.Msg("=================================================");
79 | foreach (var filePath in excels)
80 | {
81 | _genSingleFileImpl(filePath, exportDir, fmt);
82 | }
83 | }
84 | #endregion
85 |
86 | public void addMessage(string msg, Color color)
87 | {
88 | if (console != null)
89 | console.addMessage(msg, color);
90 | }
91 |
92 | public void refreshButtonGenAll()
93 | {
94 | switch (AppData.Config.ExportFormat)
95 | {
96 | case TableExportFormat.Unknown:
97 | btnGenAll.IsEnabled = false;
98 | btnGenAll.Content = "请选择生成的数据格式";
99 | break;
100 | default:
101 | btnGenAll.IsEnabled = true;
102 | btnGenAll.Content = string.Format(btnGenAll.Tag as string, AppData.Config.ExportFormat.ToString());
103 | break;
104 | }
105 | }
106 |
107 | public void editForExcel(string filePath)
108 | {
109 | if (!File.Exists(filePath))
110 | {
111 | Log.Err("源文件不存在! {0}", filePath);
112 | return;
113 | }
114 |
115 | try
116 | {
117 | TableExcelData data = TableExcelReader.loadFromExcel(filePath);
118 | openExcelView(data, filePath);
119 | }
120 | catch (System.Exception ex)
121 | {
122 | Log.Err(ex.Message);
123 | }
124 | }
125 |
126 | public void openExcelView(TableExcelData data, string filePath)
127 | {
128 | var panel = new FrameExcelView();
129 | panel.refreshUIByTableExcelData(data);
130 | panel.setFilePath(filePath);
131 |
132 | var pw = new PopupWindow(panel);
133 | pw.ResizeMode = ResizeMode.CanResize;
134 | pw.Owner = Window.GetWindow(this);
135 | pw.Title = string.Format("查看配置表 -- {0}", filePath);
136 | pw.MinWidth = 600;
137 | pw.MinHeight = 400;
138 | if (pw.ShowDialog() == true)
139 | {
140 | }
141 | }
142 |
143 | public void rectifyFileFormat(string filePath)
144 | {
145 | if (!File.Exists(filePath))
146 | {
147 | Log.Err("源文件不存在! {0}", filePath);
148 | return;
149 | }
150 |
151 | Log.Msg("=================================================");
152 |
153 | try
154 | {
155 | Log.Msg("正在优化 {0}", filePath);
156 | TableExcelData data = TableExcelReader.loadFromExcel(filePath);
157 | TableExcelWriter.genExcel(data, filePath);
158 | Log.Msg("优化完毕!");
159 | }
160 | catch (System.Exception ex)
161 | {
162 | Log.Err(ex.Message);
163 | }
164 | }
165 |
166 | public void rectifyAllFileFormat(List files)
167 | {
168 | if (files.Count == 0)
169 | {
170 | Log.Wrn("没有要优化的文件");
171 | return;
172 | }
173 |
174 | Log.Msg("=================================================");
175 | foreach (var filePath in files)
176 | {
177 | try
178 | {
179 | Log.Msg("正在优化 {0}", filePath);
180 | TableExcelData data = TableExcelReader.loadFromExcel(filePath);
181 | TableExcelWriter.genExcel(data, filePath);
182 | }
183 | catch (System.Exception ex)
184 | {
185 | Log.Err(ex.Message);
186 | }
187 | }
188 | Log.Msg("优化完毕!");
189 | }
190 |
191 | public void genSingleFile(string filePath, string exportDir, TableExportFormat fmt)
192 | {
193 | if (!File.Exists(filePath))
194 | {
195 | Log.Err("源文件不存在! {0}", filePath);
196 | return;
197 | }
198 |
199 | if (!Directory.Exists(exportDir))
200 | {
201 | Log.Err("导出目录不存在! {0}", exportDir);
202 | return;
203 | }
204 |
205 | if (fmt == TableExportFormat.Unknown)
206 | {
207 | Log.Err("导出数据格式不合法!");
208 | return;
209 | }
210 |
211 | Log.Msg("=================================================");
212 | _genSingleFileImpl(filePath, exportDir, fmt);
213 | }
214 |
215 | private void _genSingleFileImpl(string filePath, string exportDir, TableExportFormat fmt)
216 | {
217 | Log.Msg("正在分析 {0}", filePath);
218 | try
219 | {
220 | TableExcelData data = TableExcelReader.loadFromExcel(filePath);
221 | string errmsg;
222 | if (!data.checkUnique(out errmsg))
223 | Log.Wrn(errmsg);
224 | switch (fmt)
225 | {
226 | case TableExportFormat.Dat:
227 | {
228 | var exportPath = Path.Combine(exportDir, string.Format("{0}.exdat", Path.GetFileNameWithoutExtension(filePath)));
229 | TableExcelExportDat.exportExcelFile(data, exportPath);
230 | }
231 | break;
232 | case TableExportFormat.Json:
233 | {
234 | var exportPath = Path.Combine(exportDir, string.Format("{0}.json", Path.GetFileNameWithoutExtension(filePath)));
235 | TableExcelExportJson.exportExcelFile(data, exportPath);
236 | }
237 | break;
238 | case TableExportFormat.Xml:
239 | {
240 | var exportPath = Path.Combine(exportDir, string.Format("{0}.xml", Path.GetFileNameWithoutExtension(filePath)));
241 | TableExcelExportXml.exportExcelFile(data, exportPath);
242 | }
243 | break;
244 | case TableExportFormat.Lua:
245 | {
246 | var exportPath = Path.Combine(exportDir, string.Format("{0}.lua", Path.GetFileNameWithoutExtension(filePath)));
247 | TableExcelExportLua.exportExcelFile(data, exportPath);
248 | }
249 | break;
250 | }
251 | Log.Msg("生成成功");
252 | }
253 | catch (System.Exception ex)
254 | {
255 | Log.Err(ex.Message);
256 | }
257 | }
258 |
259 | private void _flipHelpPanel()
260 | {
261 | var hp = new HelperPanel();
262 | var pw = new PopupWindow(hp);
263 | pw.Owner = Window.GetWindow(this);
264 | pw.Title = "使用说明";
265 | pw.ShowDialog();
266 | }
267 |
268 | private void _flipMoreSettingPanel()
269 | {
270 | var fsm = new FrameSettingMore();
271 | var pw = new PopupWindow(fsm);
272 | pw.Owner = Window.GetWindow(this);
273 | pw.Title = "更多设置";
274 | pw.ShowDialog();
275 | }
276 | }
277 | }
278 |
--------------------------------------------------------------------------------
/tablegen2/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Windows;
3 |
4 | namespace tablegen2
5 | {
6 | static class Program
7 | {
8 | ///
9 | /// 应用程序的主入口点。
10 | ///
11 | [STAThread]
12 | static void Main(string[] args)
13 | {
14 | ApplicationEvents.Application_Startup();
15 | if (CommandHelper.Command == CommandType.Help)
16 | {
17 | CommandHelper.processHelp();
18 | }
19 | else if (CommandHelper.Command == CommandType.OpenDatFile)
20 | {
21 | CommandHelper.processOpenDatFile();
22 | }
23 | else if (CommandHelper.Command == CommandType.OpenExcelFile)
24 | {
25 | CommandHelper.processOpenExcelFile();
26 | }
27 | else if (CommandHelper.Command == CommandType.ExportFiles)
28 | {
29 | CommandHelper.processExportFiles();
30 | }
31 | else
32 | {
33 | App app = new App();
34 | app.InitializeComponent();
35 | app.Run((Window)new MainWindow());
36 | }
37 | ApplicationEvents.Application_Exit();
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/tablegen2/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Resources;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 | using System.Windows;
6 |
7 | // 有关程序集的一般信息由以下
8 | // 控制。更改这些特性值可修改
9 | // 与程序集关联的信息。
10 | [assembly: AssemblyTitle("tablegen2")]
11 | [assembly: AssemblyDescription("")]
12 | [assembly: AssemblyConfiguration("")]
13 | [assembly: AssemblyCompany("")]
14 | [assembly: AssemblyProduct("tablegen2")]
15 | [assembly: AssemblyCopyright("Copyright © 2018")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | //将 ComVisible 设置为 false 将使此程序集中的类型
20 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
21 | //请将此类型的 ComVisible 特性设置为 true。
22 | [assembly: ComVisible(false)]
23 |
24 | //若要开始生成可本地化的应用程序,请
25 | // 中的 .csproj 文件中
26 | //例如,如果您在源文件中使用的是美国英语,
27 | //使用的是美国英语,请将 设置为 en-US。 然后取消
28 | //对以下 NeutralResourceLanguage 特性的注释。 更新
29 | //以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
30 |
31 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
32 |
33 |
34 | [assembly: ThemeInfo(
35 | ResourceDictionaryLocation.None, //主题特定资源词典所处位置
36 | //(当资源未在页面
37 | //或应用程序资源字典中找到时使用)
38 | ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
39 | //(当资源未在页面
40 | //、应用程序或任何主题专用资源字典中找到时使用)
41 | )]
42 |
43 |
44 | // 程序集的版本信息由下列四个值组成:
45 | //
46 | // 主版本
47 | // 次版本
48 | // 生成号
49 | // 修订号
50 | //
51 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
52 | // 方法是按如下所示使用“*”: :
53 | // [assembly: AssemblyVersion("1.0.*")]
54 | [assembly: AssemblyVersion("1.0.0.0")]
55 | [assembly: AssemblyFileVersion("1.0.0.0")]
56 |
--------------------------------------------------------------------------------
/tablegen2/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace tablegen2.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// 一个强类型的资源类,用于查找本地化的字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// 返回此类使用的缓存的 ResourceManager 实例。
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("tablegen2.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// 使用此强类型资源类,为所有资源查找
51 | /// 重写当前线程的 CurrentUICulture 属性。
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/tablegen2/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
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 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/tablegen2/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace tablegen2.Properties {
12 |
13 |
14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
17 |
18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
19 |
20 | public static Settings Default {
21 | get {
22 | return defaultInstance;
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/tablegen2/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/tablegen2/app.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/tablegen2/app.ico
--------------------------------------------------------------------------------
/tablegen2/common/AppData.cs:
--------------------------------------------------------------------------------
1 | using tablegen2.logic;
2 |
3 | namespace tablegen2
4 | {
5 | public static class AppData
6 | {
7 | public static MainWindow MainWindow = null;
8 | public static TableGenConfig Config = null;
9 |
10 | static AppData()
11 | {
12 | }
13 |
14 | public static void loadConfig()
15 | {
16 | Config = JsonConfig.readFromFile("config.json") ?? new TableGenConfig();
17 | //修正值
18 | if (string.IsNullOrEmpty(Config.SheetNameForField))
19 | Config.SheetNameForField = "def";
20 | if (string.IsNullOrEmpty(Config.SheetNameForData))
21 | Config.SheetNameForData = "data";
22 | }
23 | public static void saveConfig()
24 | {
25 | JsonConfig.writeToFile("config.json", Config);
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/tablegen2/common/BinaryExtension.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using System.Text;
3 |
4 | namespace tablegen2
5 | {
6 | public static class BinaryExtension
7 | {
8 | public static void WriteUtf8String(this BinaryWriter bw, string str)
9 | {
10 | bw.Write(Encoding.UTF8.GetBytes(str));
11 | bw.Write((byte)0);
12 | }
13 |
14 | public static string ReadUtf8String(this BinaryReader br)
15 | {
16 | MemoryStream ms = new MemoryStream();
17 | while (true)
18 | {
19 | byte a = br.ReadByte();
20 | if (a == 0)
21 | break;
22 | ms.WriteByte(a);
23 | }
24 | return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/tablegen2/common/FrameworkExtension.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Windows.Controls;
3 | using System.Windows;
4 | using System.Windows.Media;
5 | using System.Linq;
6 |
7 | namespace tablegen2
8 | {
9 | internal static class FrameworkExtension
10 | {
11 | public static Vector GetOffsetFromRelativeParent(this FrameworkElement e, FrameworkElement p)
12 | {
13 | p.UpdateLayout();
14 |
15 | var r = new Vector(0, 0);
16 | var t = e;
17 | while (t != p)
18 | {
19 | if (t == null)
20 | throw new Exception("GetOffsetFromRelativeParent 异常!");
21 |
22 | var v = VisualTreeHelper.GetOffset(t);
23 | r += v;
24 | t = VisualTreeHelper.GetParent(t) as FrameworkElement;
25 | }
26 |
27 | return r;
28 | }
29 |
30 | public static void MakesureChildVisible(this ScrollViewer sv, FrameworkElement child)
31 | {
32 | if (child == null)
33 | return;
34 |
35 | var reserve = 20;
36 |
37 | var p = child.GetOffsetFromRelativeParent(sv);
38 | p.X += sv.HorizontalOffset;
39 | p.Y += sv.VerticalOffset;
40 |
41 | if (sv.HorizontalScrollBarVisibility != ScrollBarVisibility.Disabled)
42 | {
43 | var x1 = p.X - reserve;
44 | var x2 = p.X + child.ActualWidth + reserve;
45 | var offsetx = sv.HorizontalOffset;
46 | var width = sv.ActualWidth;
47 | if (x1 < offsetx)
48 | offsetx = x1;
49 | else if (offsetx + width < x2)
50 | offsetx = x2 - width;
51 | sv.ScrollToHorizontalOffset(offsetx);
52 | }
53 |
54 | if (sv.VerticalScrollBarVisibility != ScrollBarVisibility.Disabled)
55 | {
56 | var y1 = p.Y - reserve;
57 | var y2 = p.Y + child.ActualHeight + reserve;
58 | var offsety = sv.VerticalOffset;
59 | var height = sv.ActualHeight;
60 | if (y1 < offsety)
61 | offsety = y1;
62 | else if (offsety + height < y2)
63 | offsety = y2 - height;
64 | sv.ScrollToVerticalOffset(offsety);
65 | }
66 | }
67 |
68 | public static void SelectComboBoxItemByTag(this ComboBox cb, string tagString)
69 | {
70 | cb.SelectedItem = cb.Items.Cast().FirstOrDefault(a => (a.Tag as string) == tagString);
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/tablegen2/common/GzipHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.IO.Compression;
4 |
5 | namespace tablegen2
6 | {
7 | internal static class GzipHelper
8 | {
9 | public static byte[] processGZipEncode(byte[] content)
10 | {
11 | return processGZipEncode(content, content.Length);
12 | }
13 |
14 | public static byte[] processGZipEncode(byte[] content, int length)
15 | {
16 | var ms = new MemoryStream();
17 | ms.Seek(0, SeekOrigin.Begin);
18 | var zip = new GZipStream(ms, CompressionMode.Compress, true);
19 | zip.Write(content, 0, length);
20 | zip.Close();
21 |
22 | var r = new byte[ms.Length];
23 | Array.Copy(ms.GetBuffer(), r, ms.Length);
24 |
25 | ms.Close();
26 |
27 | return r;
28 | }
29 |
30 | public static byte[] processGZipDecode(byte[] content)
31 | {
32 | return processGZipDecode(content, content.Length);
33 | }
34 |
35 | public static byte[] processGZipDecode(byte[] content, int length)
36 | {
37 | var wms = new MemoryStream();
38 |
39 | var ms = new MemoryStream(content, 0, length);
40 | ms.Seek(0, SeekOrigin.Begin);
41 | var zip = new GZipStream(ms, CompressionMode.Decompress, true);
42 |
43 | var buf = new byte[4096];
44 | int n;
45 | while ((n = zip.Read(buf, 0, buf.Length)) != 0)
46 | {
47 | wms.Write(buf, 0, n);
48 | }
49 |
50 | zip.Close();
51 | ms.Close();
52 |
53 | var r = new byte[wms.Length];
54 | Array.Copy(wms.GetBuffer(), r, wms.Length);
55 | return r;
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/tablegen2/common/JsonConfig.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using System.Text;
3 | using System.Web.Script.Serialization;
4 |
5 | namespace tablegen2
6 | {
7 | internal static class JsonConfig
8 | {
9 | public static void writeToFile(string fileName, object target)
10 | {
11 | var jss = new JavaScriptSerializer();
12 | var content = jss.Serialize(target);
13 | var filePath = Path.Combine(Util.WorkPath, fileName);
14 | File.WriteAllBytes(filePath, Encoding.UTF8.GetBytes(content));
15 | }
16 |
17 | public static T readFromFile(string fileName)
18 | {
19 | try
20 | {
21 | var filePath = Path.Combine(Util.WorkPath, fileName);
22 | var fileContent = File.ReadAllBytes(filePath);
23 | var content = Encoding.UTF8.GetString(fileContent);
24 | var jss = new JavaScriptSerializer();
25 | return jss.Deserialize(content);
26 | }
27 | catch (System.Exception)
28 | {
29 | }
30 |
31 | return default(T);
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/tablegen2/common/Log.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows.Media;
7 |
8 | namespace tablegen2
9 | {
10 | internal static class Log
11 | {
12 | public static void Msg(string msg, params object[] args)
13 | {
14 | var mw = App.Current.MainWindow as MainWindow;
15 | if (mw != null)
16 | mw.addMessage(string.Format(msg, args), Color.FromArgb(0xFF, 0, 200, 0));
17 | }
18 |
19 | public static void Wrn(string msg, params object[] args)
20 | {
21 | var mw = App.Current.MainWindow as MainWindow;
22 | if (mw != null)
23 | mw.addMessage(string.Format(msg, args), Colors.Yellow);
24 | }
25 |
26 | public static void Err(string msg, params object[] args)
27 | {
28 | var mw = App.Current.MainWindow as MainWindow;
29 | if (mw != null)
30 | mw.addMessage(string.Format(msg, args), Color.FromArgb(0xFF, 255, 50, 50));
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/tablegen2/common/MessageBoxExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace tablegen2
4 | {
5 | public static class MessageBoxExtensions
6 | {
7 | public static void InfBox(this FrameworkElement owner, string str, params object[] args)
8 | {
9 | MessageBox.Show(
10 | Window.GetWindow(owner),
11 | string.Format(str, args),
12 | "提示",
13 | MessageBoxButton.OK,
14 | MessageBoxImage.Information);
15 | }
16 |
17 | public static void WrnBox(this FrameworkElement owner, string str, params object[] args)
18 | {
19 | MessageBox.Show(
20 | Window.GetWindow(owner),
21 | string.Format(str, args),
22 | "警告",
23 | MessageBoxButton.OK,
24 | MessageBoxImage.Warning);
25 | }
26 |
27 | public static void ErrBox(this FrameworkElement owner, string str, params object[] args)
28 | {
29 | MessageBox.Show(
30 | Window.GetWindow(owner),
31 | string.Format(str, args),
32 | "错误",
33 | MessageBoxButton.OK,
34 | MessageBoxImage.Error);
35 | }
36 |
37 | public static bool YesNoBox(this FrameworkElement owner, string str, params object[] args)
38 | {
39 | return MessageBox.Show(
40 | Window.GetWindow(owner),
41 | string.Format(str, args),
42 | "请选择",
43 | MessageBoxButton.YesNo,
44 | MessageBoxImage.Question) == MessageBoxResult.Yes;
45 | }
46 |
47 | public static bool? YesNoCancelBox(this FrameworkElement owner, string str, params object[] args)
48 | {
49 | var mbr = MessageBox.Show(
50 | Window.GetWindow(owner),
51 | string.Format(str, args),
52 | "请选择",
53 | MessageBoxButton.YesNoCancel,
54 | MessageBoxImage.Question);
55 | if (mbr == MessageBoxResult.Yes)
56 | return true;
57 | if (mbr == MessageBoxResult.No)
58 | return false;
59 | return null;
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/tablegen2/common/Util.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Security.Cryptography;
4 | using System.Text;
5 | using System.Threading;
6 |
7 | namespace tablegen2
8 | {
9 | internal static class Util
10 | {
11 | ///
12 | /// 获取环境目录
13 | ///
14 | public static string WorkPath
15 | {
16 | get { return System.AppDomain.CurrentDomain.BaseDirectory; }
17 | }
18 |
19 | public static string ModulePath
20 | {
21 | get { return System.Windows.Forms.Application.ExecutablePath; }
22 | }
23 |
24 | ///
25 | /// 确保此文件夹存在
26 | ///
27 | /// 文件夹路径
28 | public static void MakesureFolderExist(string dir)
29 | {
30 | if (!Directory.Exists(dir))
31 | Directory.CreateDirectory(dir);
32 | }
33 |
34 | ///
35 | /// 打开文件夹
36 | ///
37 | /// 目录
38 | public static void OpenDir(string dir)
39 | {
40 | try
41 | {
42 | if (!System.IO.Directory.Exists(dir))
43 | return;
44 |
45 | System.Diagnostics.Process.Start("explorer.exe", dir);
46 | }
47 | catch (System.Exception)
48 | {
49 | }
50 | }
51 |
52 | ///
53 | /// 打开某个目录并选中对应文件
54 | ///
55 | /// 文件路径
56 | public static void OpenDirFile(string path)
57 | {
58 | try
59 | {
60 | if (!System.IO.File.Exists(path) && !System.IO.Directory.Exists(path))
61 | return;
62 |
63 | System.Diagnostics.Process.Start("explorer.exe", string.Format("/select,\"{0}\"", path));
64 | }
65 | catch (System.Exception)
66 | {
67 | }
68 | }
69 |
70 | ///
71 | /// 获取1970到现在的天数
72 | ///
73 | ///
74 | public static int GetDayFrom1970()
75 | {
76 | DateTime tm = new DateTime(1970, 1, 1);
77 | TimeSpan ts = DateTime.Now - tm;
78 | return ts.Days;
79 | }
80 |
81 | ///
82 | /// 取得随机数
83 | ///
84 | private static Random rdm_ = new Random(Environment.TickCount);
85 | public static int GetRandom(int min, int max)
86 | {
87 | return rdm_.Next(min, max);
88 | }
89 |
90 | ///
91 | /// 计算缓冲区的Md5
92 | ///
93 | public static string MdBuffer(byte[] buffer)
94 | {
95 | StringBuilder sb = new StringBuilder();
96 | MD5CryptoServiceProvider svr = new MD5CryptoServiceProvider();
97 | foreach (byte b in svr.ComputeHash(buffer))
98 | sb.Append(b.ToString("X2"));
99 | return sb.ToString();
100 | }
101 |
102 | ///
103 | /// 计算字符串的UTF8格式Md5值
104 | ///
105 | public static string MdString(string str)
106 | {
107 | return MdBuffer(Encoding.UTF8.GetBytes(str));
108 | }
109 |
110 | ///
111 | /// 计算文件的Md5值
112 | ///
113 | public static string MdFile(string path)
114 | {
115 | using (var fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
116 | {
117 | StringBuilder sb = new StringBuilder();
118 | MD5CryptoServiceProvider svr = new MD5CryptoServiceProvider();
119 | foreach (byte b in svr.ComputeHash(fs))
120 | sb.Append(b.ToString("X2"));
121 | return sb.ToString();
122 | }
123 | }
124 |
125 | public static string ToFormatLength(long length)
126 | {
127 | string s = "";
128 | if (length < 1024)
129 | {
130 | s = String.Format("{0} KB", Math.Ceiling(length / 1024.0f));
131 | }
132 | else if (length < 1024 * 1024)
133 | {
134 | s = String.Format("{0:N2} KB", length / 1024.0f);
135 | }
136 | else if (length < 1024 * 1024 * 1024)
137 | {
138 | s = String.Format("{0:N2} MB", length / 1024.0f / 1024.0f);
139 | }
140 | else
141 | {
142 | s = String.Format("{0:N2} MB", length / 1024.0f / 1024.0f / 1024.0f);
143 | }
144 |
145 | return s;
146 | }
147 |
148 | ///
149 | /// 删除某个目录,最大删除清理
150 | ///
151 | /// 要删除的目录
152 | /// 成功或失败
153 | public static bool RemoveDirectory(string dir)
154 | {
155 | bool r = true;
156 |
157 | if (Directory.Exists(dir))
158 | {
159 | foreach (var s in Directory.GetFiles(dir))
160 | {
161 | try
162 | {
163 | File.Delete(s);
164 | Thread.Sleep(1);
165 | }
166 | catch
167 | {
168 | r = false;
169 | }
170 | }
171 |
172 | foreach (var s in Directory.GetDirectories(dir))
173 | {
174 | if (!RemoveDirectory(s))
175 | {
176 | r = false;
177 | continue;
178 | }
179 |
180 | Directory.Delete(s);
181 | Thread.Sleep(1);
182 | }
183 | }
184 |
185 | return r;
186 | }
187 |
188 | public static bool IsStringNumber(string s)
189 | {
190 | if (string.IsNullOrEmpty(s))
191 | return false;
192 |
193 | foreach (var c in s)
194 | {
195 | if (!char.IsNumber(c))
196 | return false;
197 | }
198 | return true;
199 | }
200 |
201 | public static void performClick(System.Windows.Controls.Button btn)
202 | {
203 | btn.RaiseEvent(new System.Windows.RoutedEventArgs(System.Windows.Controls.Button.ClickEvent, btn));
204 | }
205 | }
206 | }
207 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/ButtonDark.xaml:
--------------------------------------------------------------------------------
1 |
55 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/ButtonDark.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows.Controls;
2 |
3 | namespace tablegen2.layouts
4 | {
5 | ///
6 | /// DarkButton.xaml 的交互逻辑
7 | ///
8 | public partial class ButtonDark : Button
9 | {
10 | public ButtonDark()
11 | {
12 | InitializeComponent();
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/ButtonLight.xaml:
--------------------------------------------------------------------------------
1 |
57 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/ButtonLight.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows.Controls;
2 |
3 | namespace tablegen2.layouts
4 | {
5 | ///
6 | /// LightButton.xaml 的交互逻辑
7 | ///
8 | public partial class ButtonLight : Button
9 | {
10 | public ButtonLight()
11 | {
12 | InitializeComponent();
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/HelperPanel.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
19 |
20 |
21 |
24 |
25 |
27 |
28 |
29 |
30 |
31 |
36 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/HelperPanel.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 |
4 | namespace tablegen2.layouts
5 | {
6 | ///
7 | /// HelperPanel.xaml 的交互逻辑
8 | ///
9 | public partial class HelperPanel : UserControl
10 | {
11 | public static readonly string HelpString =
12 | @"1.Excel格式说明:
13 |
14 | * 目前字段类型支持
15 | string(字符串)
16 | int(整型)
17 | double(小数)
18 |
19 | * 每张表须包含两个字段名称固定且值不能重复的字段
20 | Id(全局唯一数字索引)
21 | KeyName(全局唯一字符串索引)
22 |
23 | * 每张表须包含两个工作簿
24 | 字段工作簿(用于声明字段名称、字段类型、字段描述)
25 | 数据工作簿(用于填充整张表的行数据)
26 |
27 | 2.工具操作说明:
28 |
29 | * 用户配置栏
30 | 配置目录----Excel表所在的目录
31 | 输出目录----生成数据文件的存放目录
32 | 输出格式----选择生成数据文件的格式
33 |
34 | * 左侧列表栏
35 | 可使用右上角的‘+’按钮通过可视化界面来新建Excel表格文件
36 | 也可以在空白地方右键使用[新建Excel表...]命令来新建表格
37 | 可使用右键菜单中的[美化Excel表]命令来规范化Excel文件
38 | 可使用右键菜单中的[生成数据]命令来单独生成某个数据表文件
39 | 可使用右键菜单中的[编辑Excel...]命令通过可视化界面来操作数据内容
40 |
41 | * 右侧输出栏
42 | 在执行命令时,会将执行过程中的日志信息打印输出到该窗口中
43 |
44 | 3.通过命令行启动说明:
45 |
46 | * 使用工具查看并编辑指定Excel文件
47 | tablegen2.exe excelFullPath.xls(.xlsx)
48 |
49 | * 使用工具查看并编辑指定.exdat(加密数据格式)文件
50 | tablegen2.exe exdatFullPath.exdat
51 |
52 | * 使用工具将Excel文件或所在的整个目录导出到指定格式的数据文件
53 | tablegen2.exe -i excelFullPath|excelDir -o outputDir -t xml|json|lua|dat
54 | ";
55 | public HelperPanel()
56 | {
57 | InitializeComponent();
58 | setString(HelpString);
59 | }
60 |
61 | public void setString(string str)
62 | {
63 | txt.Text = str;
64 | }
65 |
66 | private void btnClose_Click(object sender, RoutedEventArgs e)
67 | {
68 | Window.GetWindow(this).DialogResult = true;
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/ListItemBase.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 |
4 | namespace tablegen2.layouts
5 | {
6 | public class ListItemBase : UserControl
7 | {
8 | //条目是否选中
9 | public static readonly DependencyProperty IsSelectedProperty;
10 | static ListItemBase()
11 | {
12 | IsSelectedProperty = DependencyProperty.Register(
13 | "IsSelected",
14 | typeof(bool),
15 | typeof(ListItemBase),
16 | new FrameworkPropertyMetadata(false, OnIsSelectedPropertyChanged),
17 | null);
18 | }
19 |
20 | //选中状态发生变化
21 | private static void OnIsSelectedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
22 | {
23 | //(d as TableListItemBase).OnSelectedChanged((bool)e.NewValue);
24 | }
25 |
26 | public bool IsSelected
27 | {
28 | get { return (bool)GetValue(IsSelectedProperty); }
29 | set { SetValue(IsSelectedProperty, value); }
30 | }
31 |
32 | public virtual void RefreshByTableInterface()
33 | {
34 |
35 | }
36 |
37 | //public abstract void OnSelectedChanged(bool val);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/PopupWindow.xaml:
--------------------------------------------------------------------------------
1 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/PopupWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Windows;
3 | using System.Windows.Controls;
4 | using System.Windows.Input;
5 |
6 | namespace tablegen2.layouts
7 | {
8 | ///
9 | /// PopupWindow.xaml 的交互逻辑
10 | ///
11 | public partial class PopupWindow : Window
12 | {
13 | public bool IsEscapeClose { get; set; }
14 | public event Func PreClosingEvent;
15 | public UserControl Panel { get; internal set; }
16 |
17 | public PopupWindow(UserControl uc)
18 | {
19 | InitializeComponent();
20 | gridContainer.Children.Add(uc);
21 | IsEscapeClose = true;
22 | Panel = uc;
23 |
24 | this.MaxWidth = SystemParameters.WorkArea.Width;
25 | this.MaxHeight = SystemParameters.WorkArea.Height;
26 | this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.SystemIdle,
27 | new Action(() =>
28 | {
29 | this.SizeToContent = SizeToContent.Manual;
30 | this.MaxWidth = System.Double.PositiveInfinity;
31 | this.MaxHeight = System.Double.PositiveInfinity;
32 | }));
33 | }
34 |
35 | private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
36 | {
37 | if (IsEscapeClose && e.Key == Key.Escape)
38 | {
39 | e.Handled = true;
40 | this.Close();
41 | }
42 | }
43 |
44 | protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
45 | {
46 | if (PreClosingEvent != null && !PreClosingEvent.Invoke())
47 | e.Cancel = true;
48 | else
49 | base.OnClosing(e);
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/WaitingControl.xaml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
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 |
--------------------------------------------------------------------------------
/tablegen2/layouts/common/WaitingControl.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading;
3 | using System.Windows;
4 | using System.Windows.Controls;
5 | using System.Windows.Input;
6 | using System.Windows.Media.Animation;
7 | using System.Windows.Threading;
8 |
9 | namespace tablegen2.layouts
10 | {
11 | ///
12 | /// WaitingControl.xaml 的交互逻辑
13 | ///
14 | public partial class WaitingControl : UserControl
15 | {
16 | private bool is_busy_;
17 | public int MinElapse { get; set; }
18 |
19 | public WaitingControl()
20 | {
21 | is_busy_ = false;
22 | MinElapse = 500;
23 | InitializeComponent();
24 | }
25 |
26 | public void BeginAction(Action func, Action callback)
27 | {
28 | if (is_busy_)
29 | {
30 | throw new Exception("Waiting Control is busy now, can't start new action!");
31 | }
32 |
33 | var sb = this.Resources["sbStory"] as Storyboard;
34 | sb.Begin();
35 |
36 | this.Visibility = Visibility.Visible;
37 | this.Focus();
38 |
39 | is_busy_ = true;
40 | Action f = () =>
41 | {
42 | int tick = Environment.TickCount;
43 |
44 | func();
45 |
46 | while (Environment.TickCount - tick < MinElapse)
47 | Thread.Sleep(1);
48 |
49 | this.Dispatcher.Invoke(
50 | DispatcherPriority.Background,
51 | new Action(() =>
52 | {
53 | this.Visibility = Visibility.Hidden;
54 | sb.Stop();
55 | if (callback != null)
56 | callback.Invoke();
57 | is_busy_ = false;
58 | }));
59 | };
60 |
61 | var th = new Thread(new ThreadStart(f));
62 | th.Start();
63 | }
64 |
65 | public bool IsBusy
66 | {
67 | get { return is_busy_; }
68 | }
69 |
70 | private void UserControl_MouseDown(object sender, MouseButtonEventArgs e)
71 | {
72 | e.Handled = true;
73 | }
74 |
75 | private void UserControl_KeyDown(object sender, KeyEventArgs e)
76 | {
77 | e.Handled = true;
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameConsole.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
23 |
24 |
25 |
26 |
28 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameConsole.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Windows.Controls;
3 | using System.Windows.Documents;
4 | using System.Windows.Media;
5 |
6 | namespace tablegen2.layouts
7 | {
8 | ///
9 | /// FrameConsole.xaml 的交互逻辑
10 | ///
11 | public partial class FrameConsole : UserControl
12 | {
13 | public FrameConsole()
14 | {
15 | InitializeComponent();
16 | }
17 |
18 | public void addMessage(string msg, Color color)
19 | {
20 | Run run = new Run()
21 | {
22 | Text = string.Format("{0} {1}\n", DateTime.Now.ToString("HH:mm:ss"), msg),
23 | Foreground = new SolidColorBrush(color),
24 | };
25 | phMessage.Inlines.Add(run);
26 | rtxt.ScrollToEnd();
27 | }
28 |
29 | public void clearMessage()
30 | {
31 | phMessage.Inlines.Clear();
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameExcelView.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
18 |
19 |
20 |
21 |
22 |
25 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameExcelView.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Data;
3 | using System.Linq;
4 | using System.Windows;
5 | using System.Windows.Controls;
6 | using tablegen2.logic;
7 |
8 | namespace tablegen2.layouts
9 | {
10 | ///
11 | /// FrameExcelView.xaml 的交互逻辑
12 | ///
13 | public partial class FrameExcelView : UserControl
14 | {
15 | private TableExcelData data_;
16 | private string filePath_;
17 |
18 | public FrameExcelView()
19 | {
20 | InitializeComponent();
21 | }
22 |
23 | public void setFilePath(string filePath)
24 | {
25 | filePath_ = filePath;
26 | }
27 |
28 | public void refreshUIByTableExcelData(TableExcelData data)
29 | {
30 | data_ = data;
31 |
32 | DataTable dt = new DataTable();
33 |
34 | //columns
35 | foreach (var hdr in data.Headers)
36 | {
37 | dt.Columns.Add(new DataColumn(hdr.FieldName, typeof(string)));
38 | }
39 |
40 | //rows
41 | foreach (var row in data.Rows)
42 | {
43 | DataRow dr = dt.NewRow();
44 | for (int i = 0; i < data.Headers.Count; i++)
45 | {
46 | var hdr = data.Headers[i];
47 | dr[hdr.FieldName] = row.StrList[i];
48 | }
49 | dt.Rows.Add(dr);
50 | }
51 |
52 | dataGrid1.ItemsSource = dt.DefaultView;
53 | }
54 |
55 | public void updateDataFromDataGrid()
56 | {
57 | var dv = dataGrid1.ItemsSource as DataView;
58 | var dt = dv.Table;
59 |
60 | data_.Rows.Clear();
61 | foreach (DataRow row in dt.Rows)
62 | {
63 | var lst = new List();
64 | for (int i = 0; i < data_.Headers.Count; i++)
65 | {
66 | var s = row[i].ToString();
67 | lst.Add(s);
68 | }
69 | data_.Rows.Add(new TableExcelRow() { StrList = lst });
70 | }
71 | }
72 |
73 | private void btnSave_Clicked(object sender, RoutedEventArgs e)
74 | {
75 | try
76 | {
77 | dataGrid1.CommitEdit(DataGridEditingUnit.Row, true);
78 |
79 | updateDataFromDataGrid();
80 |
81 | var fp = filePath_.ToLower();
82 | if (fp.EndsWith(".xls") || fp.EndsWith(".xlsx"))
83 | {
84 | TableExcelWriter.genExcel(data_, filePath_);
85 | }
86 | else if (fp.EndsWith(".exdat"))
87 | {
88 | TableExcelExportDat.exportExcelFile(data_, filePath_);
89 | }
90 | else if (fp.EndsWith(".json"))
91 | {
92 | TableExcelExportJson.exportExcelFile(data_, filePath_);
93 | }
94 | else if (fp.EndsWith(".xml"))
95 | {
96 | TableExcelExportXml.exportExcelFile(data_, filePath_);
97 | }
98 | else if (fp.EndsWith(".lua"))
99 | {
100 | TableExcelExportLua.exportExcelFile(data_, filePath_);
101 | }
102 | Window.GetWindow(this).Close();
103 | }
104 | catch (System.Exception ex)
105 | {
106 | this.ErrBox(ex.Message);
107 | }
108 | }
109 |
110 | private void btnSetting_Clicked(object sender, RoutedEventArgs e)
111 | {
112 | var panel = new HeaderPage();
113 | panel.IsNewFileMode = false;
114 | panel.refreshDislpay(data_.Headers);
115 |
116 | var pw = new PopupWindow(panel);
117 | pw.ResizeMode = ResizeMode.CanResize;
118 | pw.Owner = Window.GetWindow(this);
119 | pw.Title = string.Format("设置字段 -- {0}", filePath_);
120 | pw.MinWidth = 600;
121 | pw.MinHeight = 400;
122 | if (pw.ShowDialog() == true)
123 | {
124 | var headers = panel.Headers;
125 |
126 | var tmp = new TableExcelData(headers, new List());
127 | var arr = headers.Select(a => data_.Headers.FindIndex(b => b.FieldName == a.FieldName)).ToArray();
128 | foreach (var row in data_.Rows)
129 | {
130 | var trow = new TableExcelRow();
131 | trow.StrList = arr.Select(idx => idx < 0 ? string.Empty : row.StrList[idx]).ToList();
132 | tmp.Rows.Add(trow);
133 | }
134 |
135 | refreshUIByTableExcelData(tmp);
136 | }
137 | }
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameFileTree.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
23 |
26 |
27 |
28 |
30 |
31 |
32 |
33 |
34 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameFileTree.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Windows;
4 | using System.Windows.Controls;
5 | using tablegen2.logic;
6 |
7 | namespace tablegen2.layouts
8 | {
9 | ///
10 | /// FrameFileTree.xaml 的交互逻辑
11 | ///
12 | public partial class FrameFileTree : UserControl
13 | {
14 | public event Action OpenExcelRequest;
15 |
16 | public FrameFileTree()
17 | {
18 | InitializeComponent();
19 | if (AppData.Config != null)
20 | refreshExcelPath(AppData.Config.ExcelDir);
21 | lv.CreateExcelEvent += () => Util.performClick(btnAddExcel);
22 | }
23 |
24 | public IEnumerable AllExcels
25 | {
26 | get { return lv.AllExcels; }
27 | }
28 |
29 | public void refreshExcelPath(string excelPath)
30 | {
31 | if (string.IsNullOrEmpty(excelPath) || !System.IO.Directory.Exists(excelPath))
32 | {
33 | txtPath.Text = string.Empty;
34 | lv.Visibility = Visibility.Hidden;
35 | layer.Visibility = Visibility.Visible;
36 | }
37 | else
38 | {
39 | txtPath.Text = excelPath;
40 | lv.Visibility = Visibility.Visible;
41 | layer.Visibility = Visibility.Hidden;
42 | lv.refreshByDir(excelPath);
43 | }
44 | }
45 |
46 | private void btnOpenExcel_Clicked(object sender, RoutedEventArgs e)
47 | {
48 | if (OpenExcelRequest != null)
49 | OpenExcelRequest.Invoke();
50 | }
51 |
52 | private void btnAddExcel_Clicked(object sender, RoutedEventArgs e)
53 | {
54 | var panel = new HeaderPage();
55 | panel.IsNewFileMode = true;
56 | panel.ExcelDir = AppData.Config.ExcelDir;
57 | panel.refreshDislpay(new List()
58 | {
59 | new TableExcelHeader()
60 | {
61 | FieldName = "Id",
62 | FieldType = "int",
63 | FieldDesc = "唯一Id索引",
64 | },
65 | new TableExcelHeader()
66 | {
67 | FieldName = "KeyName",
68 | FieldType = "string",
69 | FieldDesc = "唯一Key索引",
70 | },
71 | });
72 |
73 | var pw = new PopupWindow(panel);
74 | pw.ResizeMode = ResizeMode.CanResize;
75 | pw.Owner = Window.GetWindow(this);
76 | pw.Title = string.Format("新建Excel表格");
77 | pw.MinWidth = 600;
78 | pw.MinHeight = 400;
79 | if (pw.ShowDialog() == true)
80 | {
81 | try
82 | {
83 | TableExcelWriter.genExcel(new TableExcelData(panel.Headers, new List()), panel.ExcelFullPath);
84 | refreshExcelPath(AppData.Config.ExcelDir);
85 | lv.selectItemByFullPath(panel.ExcelFullPath);
86 | }
87 | catch (System.Exception ex)
88 | {
89 | this.ErrBox(ex.Message);
90 | }
91 | }
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameSetting.xaml:
--------------------------------------------------------------------------------
1 |
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 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameSetting.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Linq;
4 | using System.Windows;
5 | using System.Windows.Controls;
6 | using tablegen2.logic;
7 |
8 | namespace tablegen2.layouts
9 | {
10 | ///
11 | /// FrameSetting.xaml 的交互逻辑
12 | ///
13 | public partial class FrameSetting : UserControl
14 | {
15 | public event Action ExcelDirChanged;
16 | public event Action ExportDirChanged;
17 | public event Action ExportFormatChanged;
18 | public event Action MoreSettingEvent;
19 |
20 | public FrameSetting()
21 | {
22 | InitializeComponent();
23 | if (AppData.Config != null)
24 | {
25 | txtExcelDir.Text = AppData.Config.ExcelDir;
26 | txtExportDir.Text = AppData.Config.ExportDir;
27 | cbExportFormat.SelectComboBoxItemByTag(AppData.Config.ExportFormat.ToString());
28 | }
29 | }
30 |
31 | public void browseExcelDirectory()
32 | {
33 | Util.performClick(btnBrowseExcelDir);
34 | }
35 |
36 | private void exportFormat_Selected(object sender, RoutedEventArgs e)
37 | {
38 | var item = sender as ComboBoxItem;
39 | var fmt = (TableExportFormat)Enum.Parse(typeof(TableExportFormat), item.Tag as string);
40 | if (fmt != TableExportFormat.Unknown)
41 | {
42 | AppData.Config.ExportFormat = fmt;
43 | AppData.saveConfig();
44 | if (ExportFormatChanged != null)
45 | ExportFormatChanged.Invoke();
46 | }
47 | }
48 |
49 | private void btnBrowseExcelDir_Clicked(object sender, RoutedEventArgs e)
50 | {
51 | System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
52 | dialog.Description = "请选择Excel目录";
53 | dialog.ShowNewFolderButton = true;
54 | if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
55 | {
56 | if (!string.IsNullOrEmpty(dialog.SelectedPath))
57 | {
58 | txtExcelDir.Text = dialog.SelectedPath;
59 | AppData.Config.ExcelDir = dialog.SelectedPath;
60 | AppData.saveConfig();
61 | if (ExcelDirChanged != null)
62 | ExcelDirChanged.Invoke();
63 | }
64 | }
65 | }
66 |
67 | private void btnBrowseExportDir_Clicked(object sender, RoutedEventArgs e)
68 | {
69 | System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
70 | dialog.Description = "请选择数据导出目录";
71 | dialog.ShowNewFolderButton = true;
72 | if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
73 | {
74 | if (!string.IsNullOrEmpty(dialog.SelectedPath))
75 | {
76 | txtExportDir.Text = dialog.SelectedPath;
77 | AppData.Config.ExportDir = dialog.SelectedPath;
78 | AppData.saveConfig();
79 | if (ExportDirChanged != null)
80 | ExportDirChanged.Invoke();
81 | }
82 | }
83 | }
84 |
85 | private void btnOpenExcelDir_Clicked(object sender, RoutedEventArgs e)
86 | {
87 | var dir = AppData.Config.ExcelDir;
88 | if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
89 | {
90 | this.InfBox("请先使用‘浏览’功能选择合法的配置目录");
91 | return;
92 | }
93 | Util.OpenDir(dir);
94 | }
95 |
96 | private void btnOpenExportDir_Clicked(object sender, RoutedEventArgs e)
97 | {
98 | var dir = AppData.Config.ExportDir;
99 | if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
100 | {
101 | this.InfBox("请先使用‘浏览’功能选择合法的配置目录");
102 | return;
103 | }
104 | Util.OpenDir(dir);
105 | }
106 |
107 | private void btnMoreSetting_Clicked(object sender, RoutedEventArgs e)
108 | {
109 | if (MoreSettingEvent != null)
110 | MoreSettingEvent.Invoke();
111 | }
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameSettingMore.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
27 |
28 |
29 |
31 |
32 |
33 |
34 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameSettingMore.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 |
4 | namespace tablegen2.layouts
5 | {
6 | ///
7 | /// FrameSettingMore.xaml 的交互逻辑
8 | ///
9 | public partial class FrameSettingMore : UserControl
10 | {
11 | public FrameSettingMore()
12 | {
13 | InitializeComponent();
14 | if (AppData.Config != null)
15 | {
16 | txtSheetField.Text = AppData.Config.SheetNameForField;
17 | txtSheetData.Text = AppData.Config.SheetNameForData;
18 | }
19 | }
20 |
21 | private void btnSave_Clicked(object sender, RoutedEventArgs e)
22 | {
23 | if (string.IsNullOrEmpty(txtSheetField.Text))
24 | {
25 | this.InfBox("请输入字段工作簿名称!");
26 | txtSheetField.Focus();
27 | return;
28 | }
29 |
30 | if (string.IsNullOrEmpty(txtSheetData.Text))
31 | {
32 | this.InfBox("请输入数据工作簿名称!");
33 | txtSheetField.Focus();
34 | return;
35 | }
36 |
37 | AppData.Config.SheetNameForField = txtSheetField.Text;
38 | AppData.Config.SheetNameForData = txtSheetData.Text;
39 | AppData.saveConfig();
40 | Window.GetWindow(this).DialogResult = true;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameToolBar.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/FrameToolBar.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Windows;
3 | using System.Windows.Controls;
4 |
5 | namespace tablegen2.layouts
6 | {
7 | ///
8 | /// FrameToolBar.xaml 的交互逻辑
9 | ///
10 | public partial class FrameToolBar : UserControl
11 | {
12 | public event Action OpenExcelEvent;
13 |
14 | public FrameToolBar()
15 | {
16 | InitializeComponent();
17 | }
18 |
19 | private void btnOpenExcel_Clicked(object sender, RoutedEventArgs e)
20 | {
21 | if (OpenExcelEvent != null)
22 | OpenExcelEvent.Invoke();
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/TreeListItem.xaml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
21 |
22 |
26 |
27 |
28 |
29 |
30 |
31 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/TreeListItem.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | namespace tablegen2.layouts
3 | {
4 | ///
5 | /// TreeListItem.xaml 的交互逻辑
6 | ///
7 | public partial class TreeListItem : ListItemBase
8 | {
9 | public string FullPath { get; set; }
10 |
11 | public TreeListItem()
12 | {
13 | InitializeComponent();
14 | }
15 |
16 | public void setTreeItemFile(string fullPath)
17 | {
18 | FullPath = fullPath;
19 | txtName.Text = System.IO.Path.GetFileName(fullPath);
20 |
21 | var desc = "未知大小";
22 | if (File.Exists(fullPath))
23 | {
24 | var fi = new FileInfo(fullPath);
25 | desc = Util.ToFormatLength(fi.Length);
26 | }
27 | txtDesc.Text = desc;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/TreeListView.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/tablegen2/layouts/framework/TreeListView.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Windows.Controls;
4 | using System.Windows.Input;
5 | using System.Windows;
6 | using System.Linq;
7 | using System.Windows.Data;
8 | using tablegen2.logic;
9 | using System.Collections.Generic;
10 |
11 | namespace tablegen2.layouts
12 | {
13 | ///
14 | /// TreeListView.xaml 的交互逻辑
15 | ///
16 | public partial class TreeListView : UserControl
17 | {
18 | private TreeListItem selectedItem_ = null;
19 | public event Action SelectedChangedEvent;
20 | public event Action CreateExcelEvent;
21 |
22 | public TreeListView()
23 | {
24 | InitializeComponent();
25 | }
26 |
27 | public TreeListItem SelectedItem
28 | {
29 | get { return selectedItem_; }
30 | set { _selectItem(value); }
31 | }
32 |
33 | public IEnumerable AllExcels
34 | {
35 | get { return wp.Children.Cast().Select(a => a.FullPath); }
36 | }
37 |
38 | public void refreshByDir(string dir)
39 | {
40 | if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
41 | {
42 | _selectItem(null);
43 | wp.Children.Clear();
44 | spEmpty.Visibility = Visibility.Visible;
45 | }
46 | else
47 | {
48 | _selectItem(null);
49 | wp.Children.Clear();
50 |
51 | var files = Directory.GetFiles(dir, "*.xls", SearchOption.TopDirectoryOnly).ToList();
52 | files = files.Union(Directory.GetFiles(dir, "*.xlsx", SearchOption.TopDirectoryOnly)).ToList();
53 | files.Sort((a, b) => string.Compare(Path.GetFileNameWithoutExtension(a), Path.GetFileNameWithoutExtension(b), true));
54 |
55 | spEmpty.Visibility = files.Count == 0 ? Visibility.Visible : Visibility.Hidden;
56 | foreach (var fullPath in files)
57 | {
58 | if (Path.GetFileName(fullPath).StartsWith("~$"))
59 | continue;
60 |
61 | var item = _createItem(fullPath);
62 | wp.Children.Add(item);
63 | }
64 | }
65 | }
66 |
67 | public void selectItemByFullPath(string fullPath)
68 | {
69 | _selectItem(wp.Children.Cast().FirstOrDefault(a => string.Compare(a.FullPath, fullPath, true) == 0));
70 | }
71 |
72 | private void sv_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
73 | {
74 | _selectItem(null);
75 | }
76 |
77 | private void sv_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
78 | {
79 | _selectItem(null);
80 | _flipMenuWithBackground();
81 | }
82 |
83 | private void btnCreateExcel_Clicked(object sender, RoutedEventArgs e)
84 | {
85 | if (CreateExcelEvent != null)
86 | CreateExcelEvent.Invoke();
87 | }
88 |
89 | #region 辅助函数
90 | private void _selectItem(TreeListItem item)
91 | {
92 | if (selectedItem_ != item)
93 | {
94 | if (selectedItem_ != null)
95 | selectedItem_.IsSelected = false;
96 | selectedItem_ = item;
97 | if (selectedItem_ != null)
98 | selectedItem_.IsSelected = true;
99 | if (SelectedChangedEvent != null)
100 | SelectedChangedEvent.Invoke();
101 | }
102 | if (selectedItem_ != null)
103 | sv.MakesureChildVisible(selectedItem_);
104 | }
105 | private TreeListItem _createItem(string fullPath)
106 | {
107 | var item = new TreeListItem();
108 | item.setTreeItemFile(fullPath);
109 | var binding = new Binding("ActualWidth") { Source = wp };
110 | item.SetBinding(FrameworkElement.WidthProperty, binding);
111 | item.MouseLeftButtonDown += (_s, _e) =>
112 | {
113 | _e.Handled = true;
114 | _selectItem(_s as TreeListItem);
115 | };
116 | item.MouseRightButtonDown += (_s, _e) =>
117 | {
118 | _e.Handled = true;
119 | _selectItem(_s as TreeListItem);
120 | _flipMenuWithItem(_s as TreeListItem);
121 | };
122 | item.MouseDoubleClick += (_s, _e) =>
123 | {
124 | if (_e.ChangedButton == MouseButton.Left)
125 | {
126 | _e.Handled = true;
127 | _performListItem(_s as TreeListItem);
128 | }
129 | };
130 | return item;
131 | }
132 | private void _flipMenuWithItem(TreeListItem item)
133 | {
134 | var menu = new ContextMenu();
135 |
136 | var miOpen = new MenuItem();
137 | miOpen.Header = "打开Excel(_O)";
138 | miOpen.FontWeight = FontWeights.Bold;
139 | miOpen.Click += (_s, _e) => System.Diagnostics.Process.Start(item.FullPath);
140 | menu.Items.Add(miOpen);
141 |
142 | var miEdit = new MenuItem();
143 | miEdit.Header = "编辑Excel(_E)";
144 | miEdit.Click += (_s, _e) => AppData.MainWindow.editForExcel(item.FullPath);
145 | menu.Items.Add(miEdit);
146 | menu.Items.Add(new Separator());
147 |
148 | //导出菜单选项
149 | {
150 | string menuText = string.Empty;
151 | switch (AppData.Config.ExportFormat)
152 | {
153 | case TableExportFormat.Dat:
154 | menuText = "导出Dat数据";
155 | break;
156 | case TableExportFormat.Json:
157 | menuText = "导出Json数据";
158 | break;
159 | case TableExportFormat.Xml:
160 | menuText = "导出Xml数据";
161 | break;
162 | case TableExportFormat.Lua:
163 | menuText = "导出Lua数据";
164 | break;
165 | }
166 | if (!string.IsNullOrEmpty(menuText))
167 | {
168 | var miExport = new MenuItem();
169 | miExport.Header = menuText;
170 | miExport.Click += (_s, _e) => AppData.MainWindow.genSingleFile(item.FullPath, AppData.Config.ExcelDir, AppData.Config.ExportFormat);
171 | menu.Items.Add(miExport);
172 | }
173 | }
174 |
175 | //美化Excel格式
176 | var miRectify = new MenuItem();
177 | miRectify.Header = "美化Excel表";
178 | miRectify.Click += (_s, _e) => AppData.MainWindow.rectifyFileFormat(item.FullPath);
179 | menu.Items.Add(miRectify);
180 | menu.Items.Add(new Separator());
181 |
182 | var miExplorer = new MenuItem();
183 | miExplorer.Header = "打开所在文件夹";
184 | miExplorer.Click += (_s, _e) => Util.OpenDirFile(item.FullPath);
185 | menu.Items.Add(miExplorer);
186 |
187 | menu.Placement = System.Windows.Controls.Primitives.PlacementMode.MousePoint;
188 | menu.IsOpen = true;
189 | }
190 | private void _performListItem(TreeListItem item)
191 | {
192 | System.Diagnostics.Process.Start(item.FullPath);
193 | }
194 | private void _flipMenuWithBackground()
195 | {
196 | var menu = new ContextMenu();
197 |
198 | var miRefresh = new MenuItem();
199 | miRefresh.Header = "刷新(_E)";
200 | miRefresh.Click += (_s, _e) => refreshByDir(AppData.Config.ExcelDir);
201 | menu.Items.Add(miRefresh);
202 |
203 | var miCreate = new MenuItem();
204 | miCreate.Header = "创建Excel表...";
205 | miCreate.Click += (_s, _e) =>
206 | {
207 | if (CreateExcelEvent != null)
208 | CreateExcelEvent.Invoke();
209 | };
210 | menu.Items.Add(miCreate);
211 | menu.Items.Add(new Separator());
212 |
213 | var miExcelFormat = new MenuItem();
214 | miExcelFormat.Header = "一键美化Excel表";
215 | miExcelFormat.Click += (_s, _e) => AppData.MainWindow.rectifyAllFileFormat(AllExcels.ToList());
216 | menu.Items.Add(miExcelFormat);
217 | menu.Items.Add(new Separator());
218 |
219 | var miExplorer = new MenuItem();
220 | miExplorer.Header = "打开所在文件夹";
221 | miExplorer.Click += (_s, _e) => Util.OpenDir(AppData.Config.ExcelDir);
222 | menu.Items.Add(miExplorer);
223 |
224 | menu.Placement = System.Windows.Controls.Primitives.PlacementMode.MousePoint;
225 | menu.IsOpen = true;
226 | }
227 | #endregion
228 | }
229 | }
230 |
--------------------------------------------------------------------------------
/tablegen2/layouts/header/HeaderFieldEdit.xaml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/tablegen2/layouts/header/HeaderFieldEdit.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 |
4 | namespace tablegen2.layouts
5 | {
6 | ///
7 | /// HeaderFieldEdit.xaml 的交互逻辑
8 | ///
9 | public partial class HeaderFieldEdit : UserControl
10 | {
11 | #region 依赖属性
12 | public static readonly DependencyProperty FieldNameProperty;
13 | public static readonly DependencyProperty IsFieldNameReadonlyProperty;
14 | public static readonly DependencyProperty FieldDescProperty;
15 | static HeaderFieldEdit()
16 | {
17 | FieldNameProperty = DependencyProperty.Register(
18 | "FieldName",
19 | typeof(string),
20 | typeof(HeaderFieldEdit),
21 | new FrameworkPropertyMetadata(""),
22 | null);
23 | IsFieldNameReadonlyProperty = DependencyProperty.Register(
24 | "IsFieldNameReadonly",
25 | typeof(bool),
26 | typeof(HeaderFieldEdit),
27 | new FrameworkPropertyMetadata(false),
28 | null);
29 | FieldDescProperty = DependencyProperty.Register(
30 | "FieldDesc",
31 | typeof(string),
32 | typeof(HeaderFieldEdit),
33 | new FrameworkPropertyMetadata(""),
34 | null);
35 | }
36 | public string FieldName
37 | {
38 | get { return (string)GetValue(FieldNameProperty); }
39 | set { SetValue(FieldNameProperty, value); }
40 | }
41 | public bool IsFieldNameReadonly
42 | {
43 | get { return (bool)GetValue(IsFieldNameReadonlyProperty); }
44 | set { SetValue(IsFieldNameReadonlyProperty, value); }
45 | }
46 | public string FieldDesc
47 | {
48 | get { return (string)GetValue(FieldDescProperty); }
49 | set { SetValue(FieldDescProperty, value); }
50 | }
51 | public string FieldType
52 | {
53 | get { return (cbFieldType.SelectedItem as ComboBoxItem).Tag as string; }
54 | set { cbFieldType.SelectComboBoxItemByTag(value); }
55 | }
56 | #endregion
57 |
58 | public HeaderFieldEdit()
59 | {
60 | InitializeComponent();
61 | }
62 |
63 | private void btnSave_Clicked(object sender, RoutedEventArgs e)
64 | {
65 | if (string.IsNullOrEmpty(FieldName))
66 | {
67 | this.InfBox("请填写字段名称!");
68 | txtFieldName.Focus();
69 | return;
70 | }
71 |
72 | Window.GetWindow(this).DialogResult = true;
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/tablegen2/layouts/header/HeaderListItem.xaml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
19 |
21 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/tablegen2/layouts/header/HeaderListItem.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace tablegen2.layouts
4 | {
5 | ///
6 | /// HeaderListItem.xaml 的交互逻辑
7 | ///
8 | public partial class HeaderListItem : ListItemBase
9 | {
10 | #region 依赖属性
11 | public static readonly DependencyProperty FieldNameProperty;
12 | public static readonly DependencyProperty FieldTypeProperty;
13 | public static readonly DependencyProperty FieldDescProperty;
14 | public static readonly DependencyProperty EditableProperty;
15 | static HeaderListItem()
16 | {
17 | FieldNameProperty = DependencyProperty.Register(
18 | "FieldName",
19 | typeof(string),
20 | typeof(HeaderListItem),
21 | new FrameworkPropertyMetadata(""),
22 | null);
23 | FieldTypeProperty = DependencyProperty.Register(
24 | "FieldType",
25 | typeof(string),
26 | typeof(HeaderListItem),
27 | new FrameworkPropertyMetadata(""),
28 | null);
29 | FieldDescProperty = DependencyProperty.Register(
30 | "FieldDesc",
31 | typeof(string),
32 | typeof(HeaderListItem),
33 | new FrameworkPropertyMetadata(""),
34 | null);
35 | EditableProperty = DependencyProperty.Register(
36 | "Editable",
37 | typeof(bool),
38 | typeof(HeaderListItem),
39 | new FrameworkPropertyMetadata(true),
40 | null);
41 | }
42 | public string FieldName
43 | {
44 | get { return (string)GetValue(FieldNameProperty); }
45 | set
46 | {
47 | if (value == "Id" || value == "KeyName")
48 | Editable = false;
49 | SetValue(FieldNameProperty, value);
50 | }
51 | }
52 | public string FieldType
53 | {
54 | get { return (string)GetValue(FieldTypeProperty); }
55 | set { SetValue(FieldTypeProperty, value); }
56 | }
57 | public string FieldDesc
58 | {
59 | get { return (string)GetValue(FieldDescProperty); }
60 | set { SetValue(FieldDescProperty, value); }
61 | }
62 | public bool Editable
63 | {
64 | get { return (bool)GetValue(EditableProperty); }
65 | set { SetValue(EditableProperty, value); }
66 | }
67 | #endregion
68 |
69 | public HeaderListItem()
70 | {
71 | InitializeComponent();
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/tablegen2/layouts/header/HeaderListView.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
18 |
19 |
21 |
22 |
23 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/tablegen2/layouts/header/HeaderListView.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Windows;
5 | using System.Windows.Controls;
6 | using System.Windows.Data;
7 | using System.Windows.Input;
8 | using tablegen2.logic;
9 |
10 | namespace tablegen2.layouts
11 | {
12 | ///
13 | /// HeaderListView.xaml 的交互逻辑
14 | ///
15 | public partial class HeaderListView : UserControl
16 | {
17 | private List items_ = new List();
18 | private HeaderListItem selectedItem_ = null;
19 |
20 | public event Action SelectedChangedEvent;
21 | public event Action AddCopyEvent;
22 | public event Action EditEvent;
23 | public event Action DeleteEvent;
24 |
25 | public HeaderListView()
26 | {
27 | InitializeComponent();
28 | _refreshDisplayTip();
29 | wp.SizeChanged += (_s, _e) => _refreshListViewTip();
30 | }
31 |
32 | public IEnumerable Items
33 | {
34 | get { return items_; }
35 | }
36 |
37 | public HeaderListItem SelectedItem
38 | {
39 | get { return selectedItem_; }
40 | set { _selectItem(value); }
41 | }
42 |
43 | public IEnumerable HeaderItems
44 | {
45 | get
46 | {
47 | return items_.Select(a => new TableExcelHeader()
48 | {
49 | FieldName = a.FieldName,
50 | FieldType = a.FieldType,
51 | FieldDesc = a.FieldDesc,
52 | });
53 | }
54 | }
55 |
56 | public bool isFieldNameExist(string fieldName)
57 | {
58 | return items_.Find(a => a.FieldName == fieldName) != null;
59 | }
60 |
61 | public void refreshDisplay(List headers)
62 | {
63 | _selectItem(null);
64 | items_.Clear();
65 | wp.Children.Clear();
66 | foreach (var header in headers)
67 | {
68 | var item = _createItem(header);
69 | var idx = items_.Count;
70 | items_.Insert(idx, item);
71 | wp.Children.Insert(idx, item);
72 | }
73 | _refreshDisplayTip();
74 | }
75 |
76 | public void addItem(TableExcelHeader header, bool isSelected)
77 | {
78 | var item = _createItem(header);
79 | var idx = items_.Count;
80 | items_.Insert(idx, item);
81 | wp.Children.Insert(idx, item);
82 | _refreshDisplayTip();
83 |
84 | if (isSelected)
85 | SelectedItem = item;
86 | }
87 |
88 | public void removeItem(HeaderListItem item)
89 | {
90 | if (item == selectedItem_)
91 | _selectItem(null);
92 | items_.Remove(item);
93 | wp.Children.Remove(item);
94 | _refreshDisplayTip();
95 | }
96 |
97 | public void moveUp(HeaderListItem item)
98 | {
99 | int idx = items_.IndexOf(item);
100 | if (idx < 3)
101 | return;
102 |
103 | var tmpItem = items_[idx - 1];
104 | items_[idx - 1] = item;
105 | items_[idx] = tmpItem;
106 | wp.Children.RemoveAt(idx - 1);
107 | wp.Children.Insert(idx, tmpItem);
108 | sv.MakesureChildVisible(item);
109 | }
110 |
111 | public void moveDown(HeaderListItem item)
112 | {
113 | int idx = items_.IndexOf(item);
114 | if (idx < 2 || idx == items_.Count - 1)
115 | return;
116 |
117 | var tmpItem = items_[idx + 1];
118 | items_[idx + 1] = item;
119 | items_[idx] = tmpItem;
120 | wp.Children.RemoveAt(idx + 1);
121 | wp.Children.Insert(idx, tmpItem);
122 | sv.MakesureChildVisible(item);
123 | }
124 |
125 | #region 事件
126 | private void sv_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
127 | {
128 | _selectItem(null);
129 | }
130 | private void sv_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
131 | {
132 | _selectItem(null);
133 | _flipMenuWithBackground();
134 | }
135 | private void sv_SizeChanged(object sender, SizeChangedEventArgs e)
136 | {
137 | _refreshListViewTip();
138 | }
139 | #endregion
140 |
141 | #region 辅助函数
142 | private void _refreshDisplayTip()
143 | {
144 | if (items_.Count > 0)
145 | {
146 | txtEmpty.Visibility = Visibility.Hidden;
147 | sv.Visibility = Visibility.Visible;
148 | }
149 | else
150 | {
151 | txtEmpty.Visibility = Visibility.Visible;
152 | sv.Visibility = Visibility.Hidden;
153 | }
154 | }
155 | private void _refreshListViewTip()
156 | {
157 | if (sv.ExtentHeight > sv.ActualHeight + 30)
158 | top.MaxHeight = 100;
159 | else
160 | top.MaxHeight = 0;
161 | }
162 | private void _selectItem(HeaderListItem item)
163 | {
164 | if (selectedItem_ != item)
165 | {
166 | if (selectedItem_ != null)
167 | selectedItem_.IsSelected = false;
168 | selectedItem_ = item;
169 | if (selectedItem_ != null)
170 | selectedItem_.IsSelected = true;
171 | if (SelectedChangedEvent != null)
172 | SelectedChangedEvent.Invoke(selectedItem_);
173 | }
174 | if (selectedItem_ != null)
175 | sv.MakesureChildVisible(selectedItem_);
176 | }
177 | private HeaderListItem _createItem(TableExcelHeader header)
178 | {
179 | var item = new HeaderListItem();
180 | item.FieldName = header.FieldName;
181 | item.FieldType = header.FieldType;
182 | item.FieldDesc = header.FieldDesc;
183 | var binding = new Binding("ActualWidth") { Source = wp };
184 | item.SetBinding(FrameworkElement.WidthProperty, binding);
185 | item.MouseLeftButtonDown += (_s, _e) =>
186 | {
187 | _e.Handled = true;
188 | _selectItem(_s as HeaderListItem);
189 | };
190 | item.MouseRightButtonDown += (_s, _e) =>
191 | {
192 | _e.Handled = true;
193 | _selectItem(_s as HeaderListItem);
194 | _flipMenuWithItem(_s as HeaderListItem);
195 | };
196 | item.MouseDoubleClick += (_s, _e) =>
197 | {
198 | if (_e.ChangedButton == MouseButton.Left)
199 | {
200 | _e.Handled = true;
201 | _flipEditItemPanel(_s as HeaderListItem);
202 | }
203 | };
204 | return item;
205 | }
206 | private void _flipMenuWithItem(HeaderListItem item)
207 | {
208 | var menu = new ContextMenu();
209 |
210 | var miEdit = new MenuItem();
211 | miEdit.Header = "编辑(_E)";
212 | miEdit.IsEnabled = item.Editable;
213 | miEdit.FontWeight = FontWeights.Bold;
214 | miEdit.Click += (_s, _e) => _flipEditItemPanel(item);
215 | menu.Items.Add(miEdit);
216 |
217 | var miAddCopy = new MenuItem();
218 | miAddCopy.IsEnabled = item.Editable;
219 | miAddCopy.Header = "复制添加(_A)";
220 | miAddCopy.Click += (_s, _e) =>
221 | {
222 | if (AddCopyEvent != null)
223 | AddCopyEvent.Invoke(item);
224 | };
225 | menu.Items.Add(miAddCopy);
226 |
227 | var miDelete = new MenuItem();
228 | miDelete.IsEnabled = item.Editable;
229 | miDelete.Header = "删除(_D)";
230 | miDelete.Click += (_s, _e) =>
231 | {
232 | if (DeleteEvent != null)
233 | DeleteEvent.Invoke(item);
234 | };
235 | menu.Items.Add(miDelete);
236 |
237 | menu.Placement = System.Windows.Controls.Primitives.PlacementMode.MousePoint;
238 | menu.IsOpen = true;
239 | }
240 | private void _flipMenuWithBackground()
241 | {
242 |
243 | }
244 | private void _flipEditItemPanel(HeaderListItem item)
245 | {
246 | if (item.Editable && EditEvent != null)
247 | EditEvent.Invoke(item);
248 | }
249 | #endregion
250 | }
251 | }
252 |
--------------------------------------------------------------------------------
/tablegen2/layouts/header/HeaderPage.xaml:
--------------------------------------------------------------------------------
1 |
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 |
38 |
40 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/tablegen2/layouts/header/HeaderPage.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.IO;
3 | using System.Linq;
4 | using System.Windows;
5 | using System.Windows.Controls;
6 | using tablegen2.logic;
7 |
8 | namespace tablegen2.layouts
9 | {
10 | ///
11 | /// HeaderPage.xaml 的交互逻辑
12 | ///
13 | public partial class HeaderPage : UserControl
14 | {
15 | #region 依赖属性
16 | public static readonly DependencyProperty EditableProperty;
17 | public static readonly DependencyProperty IsNewFileModeProperty;
18 | static HeaderPage()
19 | {
20 | EditableProperty = DependencyProperty.Register(
21 | "Editable",
22 | typeof(bool),
23 | typeof(HeaderPage),
24 | new FrameworkPropertyMetadata(false),
25 | null);
26 | IsNewFileModeProperty = DependencyProperty.Register(
27 | "IsNewFileMode",
28 | typeof(bool),
29 | typeof(HeaderPage),
30 | new FrameworkPropertyMetadata(false),
31 | null);
32 | }
33 | public bool Editable
34 | {
35 | get { return (bool)GetValue(EditableProperty); }
36 | set { SetValue(EditableProperty, value); }
37 | }
38 | public bool IsNewFileMode
39 | {
40 | get { return (bool)GetValue(IsNewFileModeProperty); }
41 | set { SetValue(IsNewFileModeProperty, value); }
42 | }
43 | #endregion
44 |
45 | public List Headers { get; internal set; }
46 | public string ExcelDir { get; set; }
47 | public string ExcelFullPath { get; internal set; }
48 |
49 | public HeaderPage()
50 | {
51 | InitializeComponent();
52 | lv.SelectedChangedEvent += (item) => Editable = item != null && item.Editable;
53 | lv.AddCopyEvent += (item) => itemAddCopyImpl(item);
54 | lv.EditEvent += (item) => itemEditImpl(item);
55 | lv.DeleteEvent += (item) => itemDeleteImpl(item);
56 | }
57 |
58 | public void refreshDislpay(List headers)
59 | {
60 | lv.refreshDisplay(headers);
61 | }
62 |
63 | private void btnAddNew_Clicked(object sender, RoutedEventArgs e)
64 | {
65 | var panel = new HeaderFieldEdit();
66 | panel.IsFieldNameReadonly = false;
67 |
68 | var pw = new PopupWindow(panel);
69 | pw.Owner = Window.GetWindow(this);
70 | pw.Title = string.Format("添加字段");
71 | if (pw.ShowDialog() == true)
72 | {
73 | if (lv.isFieldNameExist(panel.FieldName))
74 | {
75 | this.InfBox("该字段已存在!");
76 | return;
77 | }
78 |
79 | lv.addItem(new TableExcelHeader()
80 | {
81 | FieldName = panel.FieldName,
82 | FieldType = panel.FieldType,
83 | FieldDesc = panel.FieldDesc,
84 | }, true);
85 | }
86 | }
87 |
88 | private void btnAddCopy_Clicked(object sender, RoutedEventArgs e)
89 | {
90 | itemAddCopyImpl(lv.SelectedItem);
91 | }
92 |
93 | private void btnEdit_Clicked(object sender, RoutedEventArgs e)
94 | {
95 | itemEditImpl(lv.SelectedItem);
96 | }
97 |
98 | private void btnDelete_Clicked(object sender, RoutedEventArgs e)
99 | {
100 | itemDeleteImpl(lv.SelectedItem);
101 | }
102 |
103 | private void btnMoveUp_Clicked(object sender, RoutedEventArgs e)
104 | {
105 | lv.moveUp(lv.SelectedItem);
106 | }
107 |
108 | private void btnMoveDown_Clicked(object sender, RoutedEventArgs e)
109 | {
110 | lv.moveDown(lv.SelectedItem);
111 | }
112 |
113 | private void btnSave_Clicked(object sender, RoutedEventArgs e)
114 | {
115 | if (IsNewFileMode)
116 | {
117 | if (!Directory.Exists(ExcelDir))
118 | {
119 | this.InfBox("系统错误,Excel目录不存在!");
120 | return;
121 | }
122 |
123 | var fileName = txtFileName.Text;
124 | if (string.IsNullOrEmpty(fileName))
125 | {
126 | this.InfBox("请填写文件名称!");
127 | txtFileName.Focus();
128 | return;
129 | }
130 |
131 | var ext = Path.GetExtension(fileName).ToLower();
132 | if (ext != ".xls" && ext != ".xlsx")
133 | fileName += ".xlsx";
134 |
135 | var fullPath = Path.Combine(ExcelDir, fileName);
136 | if (File.Exists(fullPath))
137 | {
138 | this.InfBox("{0}\n该文件已存在,请重新填写!", fullPath);
139 | txtFileName.Focus();
140 | txtFileName.SelectAll();
141 | return;
142 | }
143 |
144 | ExcelFullPath = fullPath;
145 | }
146 |
147 | Headers = lv.HeaderItems.ToList();
148 | Window.GetWindow(this).DialogResult = true;
149 | }
150 |
151 | private void itemAddCopyImpl(HeaderListItem item)
152 | {
153 | var panel = new HeaderFieldEdit();
154 | panel.IsFieldNameReadonly = false;
155 | panel.FieldName = item.FieldName;
156 | panel.FieldType = item.FieldType;
157 | panel.FieldDesc = item.FieldDesc;
158 |
159 | var pw = new PopupWindow(panel);
160 | pw.Owner = Window.GetWindow(this);
161 | pw.Title = string.Format("复制添加字段");
162 | if (pw.ShowDialog() == true)
163 | {
164 | if (lv.isFieldNameExist(panel.FieldName))
165 | {
166 | this.InfBox("该字段已存在!");
167 | return;
168 | }
169 |
170 | lv.addItem(new TableExcelHeader()
171 | {
172 | FieldName = panel.FieldName,
173 | FieldType = panel.FieldType,
174 | FieldDesc = panel.FieldDesc,
175 | }, true);
176 | }
177 | }
178 | private void itemEditImpl(HeaderListItem item)
179 | {
180 | var panel = new HeaderFieldEdit();
181 | panel.IsFieldNameReadonly = true;
182 | panel.FieldName = item.FieldName;
183 | panel.FieldType = item.FieldType;
184 | panel.FieldDesc = item.FieldDesc;
185 |
186 | var pw = new PopupWindow(panel);
187 | pw.Owner = Window.GetWindow(this);
188 | pw.Title = string.Format("复制添加字段");
189 | if (pw.ShowDialog() == true)
190 | {
191 | item.FieldType = panel.FieldType;
192 | item.FieldDesc = panel.FieldDesc;
193 | }
194 | }
195 | private void itemDeleteImpl(HeaderListItem item)
196 | {
197 | if (this.YesNoBox("确定要删除该条目吗?"))
198 | {
199 | lv.removeItem(item);
200 | }
201 | }
202 | }
203 | }
204 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExcelData.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 |
4 | namespace tablegen2.logic
5 | {
6 | public class TableExcelData
7 | {
8 | private List headers_ = new List();
9 | private List rows_ = new List();
10 |
11 | public TableExcelData()
12 | {
13 | }
14 |
15 | public TableExcelData(IEnumerable headers, IEnumerable rows)
16 | {
17 | headers_ = headers.ToList();
18 | rows_ = rows.ToList();
19 | }
20 |
21 | public List Headers
22 | {
23 | get { return headers_; }
24 | }
25 |
26 | public List Rows
27 | {
28 | get { return rows_; }
29 | }
30 |
31 | public bool checkUnique(out string errmsg)
32 | {
33 | int idx1 = headers_.FindIndex(a => a.FieldName.Equals("Id"));
34 | int idx2 = headers_.FindIndex(a => a.FieldName.Equals("KeyName"));
35 | var ids = new HashSet();
36 | var keys = new HashSet();
37 | for (int i = 0; i < rows_.Count; i++)
38 | {
39 | var row = rows_[i];
40 | var strId = row.StrList[idx1];
41 | var strKeyName = row.StrList[idx2];
42 |
43 | int id;
44 | if (!int.TryParse(strId, out id))
45 | {
46 | errmsg = string.Format("第{0}行Id值非法,须为数字类型:{1}", i + 2, strId);
47 | return false;
48 | }
49 |
50 | if (string.IsNullOrEmpty(strKeyName))
51 | {
52 | errmsg = string.Format("第{0}行KeyName值为空", i + 2);
53 | return false;
54 | }
55 |
56 | if (ids.Contains(id))
57 | {
58 | errmsg = string.Format("第{0}行Id值已存在:{1}", i + 2, strId);
59 | return false;
60 | }
61 |
62 | if (keys.Contains(strKeyName))
63 | {
64 | errmsg = string.Format("第{0}行KeyName值已存在:{1}", i + 2, strKeyName);
65 | return false;
66 | }
67 |
68 | ids.Add(id);
69 | keys.Add(strKeyName);
70 | }
71 |
72 | errmsg = string.Empty;
73 | return true;
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExcelExportDat.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Text;
4 |
5 | namespace tablegen2.logic
6 | {
7 | public static class TableExcelExportDat
8 | {
9 | public static void exportExcelFile(TableExcelData data, string filePath)
10 | {
11 | const int version = 1;
12 |
13 | var ms = new MemoryStream();
14 | var bw = new BinaryWriter(ms, Encoding.UTF8);
15 | bw.Write(version);
16 |
17 | foreach (var hdr in data.Headers)
18 | {
19 | bw.WriteUtf8String(hdr.FieldName);
20 | byte ftype = 0;
21 | switch (hdr.FieldType)
22 | {
23 | case "int":
24 | ftype = 1;
25 | break;
26 | case "double":
27 | ftype = 2;
28 | break;
29 | case "string":
30 | ftype = 3;
31 | break;
32 | default:
33 | throw new Exception(string.Format("无法识别的字段类型 {0} 名称 {1}", hdr.FieldType, hdr.FieldName));
34 | }
35 | bw.Write(ftype);
36 | }
37 | bw.Write((byte)0);
38 |
39 | foreach (var row in data.Rows)
40 | {
41 | for (int i = 0; i < data.Headers.Count; i++)
42 | {
43 | var hdr = data.Headers[i];
44 | var val = row.StrList[i];
45 | switch (hdr.FieldType)
46 | {
47 | case "int":
48 | {
49 | int n = 0;
50 | int.TryParse(val, out n);
51 | bw.Write(n);
52 | }
53 | break;
54 | case "double":
55 | {
56 | double n = 0;
57 | double.TryParse(val, out n);
58 | bw.Write(n);
59 | }
60 | break;
61 | case "string":
62 | bw.WriteUtf8String(val);
63 | break;
64 | }
65 | }
66 | }
67 |
68 | if (File.Exists(filePath))
69 | File.Delete(filePath);
70 |
71 | File.WriteAllBytes(filePath, GzipHelper.processGZipEncode(ms.GetBuffer(), (int)ms.Length));
72 |
73 | bw.Close();
74 | ms.Close();
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExcelExportJson.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 | using System.Text;
4 | using Newtonsoft.Json;
5 | using System.IO;
6 |
7 | namespace tablegen2.logic
8 | {
9 | public static class TableExcelExportJson
10 | {
11 | public static void exportExcelFile(TableExcelData data, string filePath)
12 | {
13 | List> lst = data.Rows.Select(a =>
14 | {
15 | var r = new Dictionary();
16 | for (int i = 0; i < data.Headers.Count; i++)
17 | {
18 | var hdr = data.Headers[i];
19 | var val = a.StrList[i];
20 | object obj = null;
21 | switch (hdr.FieldType)
22 | {
23 | case "string":
24 | obj = val;
25 | break;
26 | case "int":
27 | {
28 | int n = 0;
29 | int.TryParse(val, out n);
30 | obj = n;
31 | }
32 | break;
33 | case "double":
34 | {
35 | double n = 0;
36 | double.TryParse(val, out n);
37 | obj = n;
38 | }
39 | break;
40 | }
41 | r[hdr.FieldName] = obj;
42 | }
43 | return r;
44 | }).ToList();
45 |
46 | string output = JsonConvert.SerializeObject(lst, Formatting.Indented);
47 | File.WriteAllBytes(filePath, Encoding.UTF8.GetBytes(output));
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExcelExportLua.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Text;
5 |
6 | namespace tablegen2.logic
7 | {
8 | public static class TableExcelExportLua
9 | {
10 | public static void exportExcelFile(TableExcelData data, string filePath)
11 | {
12 | exportLua_Impl2(data, filePath);
13 | }
14 |
15 | public static void appendFormatLineEx(StringBuilder sb, int indent, string fmtstr, params object[] args)
16 | {
17 | if (indent > 0)
18 | sb.Append(new String(' ', indent * 4));
19 | sb.AppendFormat(fmtstr, args);
20 | sb.AppendLine();
21 | }
22 |
23 | #region export for simple format
24 | private static void exportLua_Impl1(TableExcelData data, string filePath)
25 | {
26 | var sb = new StringBuilder();
27 | appendFormatLineEx(sb, 0, "local data = ");
28 | appendFormatLineEx(sb, 0, "{{");
29 | foreach (var row in data.Rows)
30 | {
31 | appendFormatLineEx(sb, 1, "{{");
32 | for (int i = 0; i < data.Headers.Count; i++)
33 | {
34 | var hdr = data.Headers[i];
35 | var val = row.StrList[i];
36 | string s = string.Empty;
37 | switch (hdr.FieldType)
38 | {
39 | case "string":
40 | s = string.Format("\"{0}\"", val);
41 | break;
42 | case "int":
43 | {
44 | int n = 0;
45 | int.TryParse(val, out n);
46 | s = n.ToString();
47 | }
48 | break;
49 | case "double":
50 | {
51 | double n = 0;
52 | double.TryParse(val, out n);
53 | s = n.ToString();
54 | }
55 | break;
56 | }
57 | appendFormatLineEx(sb, 2, "[\"{0}\"] = {1},", hdr.FieldName, s);
58 | }
59 | appendFormatLineEx(sb, 1, "}},");
60 | }
61 | appendFormatLineEx(sb, 0, "}}");
62 | sb.AppendLine();
63 | appendFormatLineEx(sb, 0, "return data");
64 |
65 | File.WriteAllBytes(filePath, Encoding.UTF8.GetBytes(sb.ToString()));
66 | }
67 | #endregion
68 |
69 | #region export for utility format
70 | private static void exportLua_Impl2(TableExcelData data, string filePath)
71 | {
72 | var sb = new StringBuilder();
73 |
74 | var ids = new List();
75 | var keys = new List();
76 |
77 | //items
78 | appendFormatLineEx(sb, 0, "local items = ");
79 | appendFormatLineEx(sb, 0, "{{");
80 | foreach (var row in data.Rows)
81 | {
82 | sb.Append(" { ");
83 | for (int i = 0; i < data.Headers.Count; i++)
84 | {
85 | var hdr = data.Headers[i];
86 | var val = row.StrList[i];
87 | string s = string.Empty;
88 | switch (hdr.FieldType)
89 | {
90 | case "string":
91 | s = string.Format("\"{0}\"", val);
92 | break;
93 | case "int":
94 | {
95 | int n = 0;
96 | int.TryParse(val, out n);
97 | s = n.ToString();
98 | }
99 | break;
100 | case "double":
101 | {
102 | double n = 0;
103 | double.TryParse(val, out n);
104 | s = n.ToString();
105 | }
106 | break;
107 | }
108 | sb.AppendFormat("{0} = {1}, ", hdr.FieldName, s);
109 |
110 | if (hdr.FieldName == "Id")
111 | ids.Add(s);
112 | else if (hdr.FieldName == "KeyName")
113 | keys.Add(s);
114 | }
115 | sb.AppendLine("},");
116 | }
117 | appendFormatLineEx(sb, 0, "}}");
118 | sb.AppendLine();
119 |
120 | //idItems
121 | appendFormatLineEx(sb, 0, "local idItems = ");
122 | appendFormatLineEx(sb, 0, "{{");
123 | for (int i = 0; i < ids.Count; i++)
124 | {
125 | appendFormatLineEx(sb, 1, "[{0}] = items[{1}],", ids[i], i + 1);
126 | }
127 | appendFormatLineEx(sb, 0, "}}");
128 | sb.AppendLine();
129 |
130 | //keyItems
131 | appendFormatLineEx(sb, 0, "local keyItems = ");
132 | appendFormatLineEx(sb, 0, "{{");
133 | for (int i = 0; i < keys.Count; i++)
134 | {
135 | appendFormatLineEx(sb, 1, "[{0}] = items[{1}],", keys[i], i + 1);
136 | }
137 | appendFormatLineEx(sb, 0, "}}");
138 | sb.AppendLine();
139 |
140 | sb.Append(
141 | @"local data = { Items = items, IdItems = idItems, KeyItems = keyItems, }
142 | function data:getById(id)
143 | return self.IdItems[id]
144 | end
145 | function data:getByKey(key)
146 | return self.KeyItems[key]
147 | end
148 | return data
149 | ");
150 |
151 | File.WriteAllBytes(filePath, Encoding.UTF8.GetBytes(sb.ToString()));
152 | }
153 | #endregion
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExcelExportXml.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using System.Text;
3 | using System.Xml;
4 |
5 | namespace tablegen2.logic
6 | {
7 | public static class TableExcelExportXml
8 | {
9 | public static void exportExcelFile(TableExcelData data, string filePath)
10 | {
11 | var doc = new XmlDocument();
12 | var root = doc.CreateElement("root");
13 | doc.AppendChild(root);
14 |
15 | foreach (var row in data.Rows)
16 | {
17 | var item = doc.CreateElement("item");
18 | for (int i = 0; i < data.Headers.Count; i++)
19 | {
20 | var hdr = data.Headers[i];
21 | var val = row.StrList[i];
22 | item.SetAttribute(hdr.FieldName, val);
23 | }
24 | root.AppendChild(item);
25 | }
26 |
27 | // 保存
28 | using (FileStream fs = File.Create(filePath))
29 | {
30 | var writer = new XmlTextWriter(fs, Encoding.UTF8);
31 | writer.Formatting = Formatting.Indented;
32 | doc.Save(writer);
33 | writer.Close();
34 | }
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExcelHeader.cs:
--------------------------------------------------------------------------------
1 | namespace tablegen2.logic
2 | {
3 | public class TableExcelHeader
4 | {
5 | public string FieldName { get; set; }
6 | public string FieldType { get; set; }
7 | public string FieldDesc { get; set; }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExcelImportDat.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 |
5 | namespace tablegen2.logic
6 | {
7 | public static class TableExcelImportDat
8 | {
9 | public static TableExcelData importFile(string filePath)
10 | {
11 | var content = GzipHelper.processGZipDecode(File.ReadAllBytes(filePath));
12 | var ms = new MemoryStream(content);
13 | var br = new BinaryReader(ms);
14 |
15 | if (br.ReadInt32() != 1)
16 | throw new Exception("无法识别的文件版本号");
17 |
18 | var r = new TableExcelData();
19 | while (true)
20 | {
21 | var fieldName = br.ReadUtf8String();
22 | if (string.IsNullOrEmpty(fieldName))
23 | break;
24 |
25 | var fieldType = string.Empty;
26 | var ftype = br.ReadByte();
27 | switch (ftype)
28 | {
29 | case 1:
30 | fieldType = "int";
31 | break;
32 | case 2:
33 | fieldType = "double";
34 | break;
35 | case 3:
36 | fieldType = "string";
37 | break;
38 | default:
39 | throw new Exception(string.Format("无法识别的字段类型 fieldName:{0} fieldType:{1}", fieldName, ftype));
40 | }
41 | r.Headers.Add(new TableExcelHeader() { FieldName = fieldName, FieldType = fieldType });
42 | }
43 |
44 | while (br.BaseStream.Position < br.BaseStream.Length)
45 | {
46 | var lst = new List();
47 | for (int i = 0; i < r.Headers.Count; i++)
48 | {
49 | var hdr = r.Headers[i];
50 | switch (hdr.FieldType)
51 | {
52 | case "string":
53 | lst.Add(br.ReadUtf8String());
54 | break;
55 | case "int":
56 | lst.Add(br.ReadInt32().ToString());
57 | break;
58 | case "double":
59 | lst.Add(br.ReadDouble().ToString());
60 | break;
61 | }
62 | }
63 | r.Rows.Add(new TableExcelRow() { StrList = lst });
64 | }
65 |
66 | return r;
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExcelReader.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using NPOI.HSSF.UserModel;
4 | using NPOI.SS.UserModel;
5 | using System.IO;
6 | using NPOI.XSSF.UserModel;
7 |
8 | namespace tablegen2.logic
9 | {
10 | public static class TableExcelReader
11 | {
12 | public static TableExcelData loadFromExcel(string filePath)
13 | {
14 | if (!File.Exists(filePath))
15 | throw new Exception(string.Format("{0} 文件不存在!", filePath));
16 |
17 | var ext = Path.GetExtension(filePath).ToLower();
18 | if (ext != ".xls" && ext != ".xlsx")
19 | throw new Exception(string.Format("无法识别的文件扩展名 {0}", ext));
20 |
21 | var headers = new List();
22 | var rows = new List();
23 |
24 | var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
25 | var workbook = ext == ".xls" ? (IWorkbook)new HSSFWorkbook(fs) : (IWorkbook)new XSSFWorkbook(fs);
26 | fs.Close();
27 |
28 | _readDataFromWorkbook(workbook, headers, rows);
29 |
30 | return new TableExcelData(headers, rows);
31 | }
32 |
33 | private static void _readDataFromWorkbook(IWorkbook wb, List headers, List rows)
34 | {
35 | var defSheetName = AppData.Config.SheetNameForField;
36 | var dataSheetName = AppData.Config.SheetNameForData;
37 |
38 | var sheet1 = wb.GetSheet(defSheetName);
39 | if (sheet1 == null)
40 | throw new Exception(string.Format("'{0}'工作簿不存在", defSheetName));
41 |
42 | var sheet2 = wb.GetSheet(dataSheetName);
43 | if (sheet2 == null)
44 | throw new Exception(string.Format("'{0}'工作簿不存在", dataSheetName));
45 |
46 | //加载字段
47 | _readHeadersFromDefSheet(sheet1, headers);
48 |
49 | var h1 = headers.Find(a => a.FieldName == "Id");
50 | if (h1 == null)
51 | throw new Exception(string.Format("'{0}'工作簿中不存在Id字段!", defSheetName));
52 |
53 | var h2 = headers.Find(a => a.FieldName == "KeyName");
54 | if (h2 == null)
55 | throw new Exception(string.Format("'{0}'工作簿中不存在KeyName字段!", defSheetName));
56 |
57 | //加载数据
58 | var headers2 = _readHeadersFromDataSheet(sheet2);
59 | var headerIndexes = new int[headers.Count];
60 | _checkFieldsSame(headers, headers2, headerIndexes);
61 |
62 | foreach (var ds in _readDataFromDataSheet(sheet2, headers2.Count))
63 | {
64 | var rowData = new List();
65 | for (int i = 0; i < headers.Count; i++)
66 | {
67 | var idx = headerIndexes[i];
68 | rowData.Add(ds[idx]);
69 | }
70 | rows.Add(new TableExcelRow() { StrList = rowData });
71 | }
72 | }
73 |
74 | private static string _convertCellToString(ICell cell)
75 | {
76 | string r = string.Empty;
77 | if (cell != null)
78 | {
79 | switch (cell.CellType)
80 | {
81 | case CellType.Boolean:
82 | r = cell.BooleanCellValue.ToString();
83 | break;
84 | case CellType.Numeric:
85 | r = cell.NumericCellValue.ToString();
86 | break;
87 | case CellType.Formula:
88 | r = cell.CellFormula;
89 | break;
90 | default:
91 | r = cell.StringCellValue;
92 | break;
93 | }
94 | }
95 | return r;
96 | }
97 |
98 | private static void _readHeadersFromDefSheet(ISheet sheet, List headers)
99 | {
100 | for (int row = 1; row <= sheet.LastRowNum; row++)
101 | {
102 | var rd = sheet.GetRow(row);
103 | if (rd == null)
104 | continue;
105 |
106 | var str1 = _convertCellToString(rd.GetCell(0));
107 | var str2 = _convertCellToString(rd.GetCell(1));
108 | var str3 = _convertCellToString(rd.GetCell(2));
109 |
110 | if (string.IsNullOrEmpty(str1) && string.IsNullOrEmpty(str2) && string.IsNullOrEmpty(str3))
111 | continue;
112 |
113 | if (!string.IsNullOrEmpty(str1) && !string.IsNullOrEmpty(str2))
114 | {
115 | headers.Add(new TableExcelHeader()
116 | {
117 | FieldName = str1,
118 | FieldType = str2,
119 | FieldDesc = str3,
120 | });
121 | continue;
122 | }
123 |
124 | throw new Exception(string.Format(
125 | "'{0}'工作簿中第{1}行数据异常,有缺失!", AppData.Config.SheetNameForField, row + 1));
126 | }
127 | }
128 |
129 | private static List _readHeadersFromDataSheet(ISheet sheet)
130 | {
131 | var r = new List();
132 | var rd = sheet.GetRow(0);
133 | for (int i = 0; i < rd.LastCellNum; i++)
134 | {
135 | var cell = rd.GetCell(i);
136 | r.Add(cell != null ? cell.StringCellValue : string.Empty);
137 | }
138 | for (int i = r.Count - 1; i >= 0; i--)
139 | {
140 | if (string.IsNullOrEmpty(r[i]))
141 | r.RemoveAt(i);
142 | else
143 | break;
144 | }
145 | int idx = r.IndexOf(string.Empty);
146 | if (idx >= 0)
147 | throw new Exception(string.Format(
148 | "'{0}'工作簿中第1行第{1}列字段名称非法", AppData.Config.SheetNameForData, idx + 1));
149 | return r;
150 | }
151 |
152 | private static void _checkFieldsSame(List headers1, List headers2, int[] indexes)
153 | {
154 | for (int i = 0; i < headers1.Count; i++)
155 | {
156 | var hd = headers1[i];
157 | var idx = headers2.IndexOf(hd.FieldName);
158 | if (idx < 0)
159 | throw new Exception(string.Format("'{0}'工作簿中不存在字段'{1}'所对应的列", AppData.Config.SheetNameForData, hd.FieldName));
160 | indexes[i] = idx;
161 | }
162 | if (headers1.Count < headers2.Count)
163 | {
164 | foreach (var s in headers2)
165 | {
166 | if (headers1.Find(a => a.FieldName == s) == null)
167 | throw new Exception(string.Format("'{0}'工作簿中的包含多余的数据列'{1}'", AppData.Config.SheetNameForData, s));
168 | }
169 | }
170 | }
171 |
172 | private static IEnumerable> _readDataFromDataSheet(ISheet sheet, int columns)
173 | {
174 | for (int i = 1; i <= sheet.LastRowNum; i++)
175 | {
176 | var rd = sheet.GetRow(i);
177 | if (rd == null)
178 | continue;
179 |
180 | var ds = new List();
181 | bool is_all_empty = true;
182 | for (int c = 0; c < columns; c++)
183 | {
184 | var val = _convertCellToString(rd.GetCell(c));
185 | if (!string.IsNullOrEmpty(val))
186 | is_all_empty = false;
187 | ds.Add(val);
188 | }
189 |
190 | if (!is_all_empty)
191 | yield return ds;
192 | }
193 | }
194 | }
195 | }
196 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExcelRow.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace tablegen2.logic
8 | {
9 | public class TableExcelRow
10 | {
11 | public List StrList { get; set; }
12 |
13 | public TableExcelRow()
14 | {
15 | StrList = new List();
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExcelWriter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using NPOI.HSSF.UserModel;
6 | using NPOI.SS.UserModel;
7 | using NPOI.XSSF.UserModel;
8 |
9 | namespace tablegen2.logic
10 | {
11 | public static class TableExcelWriter
12 | {
13 | public static void genExcel(TableExcelData data, string filePath)
14 | {
15 | Util.MakesureFolderExist(Path.GetDirectoryName(filePath));
16 |
17 | var ext = Path.GetExtension(filePath).ToLower();
18 | if (ext != ".xls" && ext != ".xlsx")
19 | throw new Exception(string.Format("无法识别的文件扩展名 {0}", ext));
20 |
21 | var workbook = ext == ".xls" ? (IWorkbook)new HSSFWorkbook() : (IWorkbook)new XSSFWorkbook();
22 | var sheet1 = workbook.CreateSheet(AppData.Config.SheetNameForField);
23 | var sheet2 = workbook.CreateSheet(AppData.Config.SheetNameForData);
24 |
25 | //创建新字体
26 | var font = workbook.CreateFont();
27 | font.IsBold = true;
28 |
29 | //创建新样式
30 | var style = workbook.CreateCellStyle();
31 | style.SetFont(font);
32 | style.FillPattern = FillPattern.SolidForeground;
33 | style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
34 |
35 | //默认样式
36 | for (short i = 0; i < workbook.NumCellStyles; i++)
37 | {
38 | workbook.GetCellStyleAt(i).VerticalAlignment = VerticalAlignment.Center;
39 | }
40 |
41 | _writeToDefSheet(sheet1, data.Headers);
42 | _writeToDataSheet(sheet2, data);
43 |
44 | var tmppath = Path.Combine(Path.GetDirectoryName(filePath),
45 | string.Format("{0}.tmp{1}", Path.GetFileNameWithoutExtension(filePath), ext));
46 | using (var fs = File.Open(tmppath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
47 | {
48 | workbook.Write(fs);
49 | }
50 | var content = File.ReadAllBytes(tmppath);
51 | File.Delete(tmppath);
52 | File.WriteAllBytes(filePath, content);
53 | }
54 |
55 | private static void _writeToSheet(ISheet sheet, IEnumerable lst)
56 | {
57 | IRow row;
58 | if (sheet.GetRow(0) == null)
59 | row = sheet.CreateRow(0);
60 | else
61 | row = sheet.CreateRow(sheet.LastRowNum + 1);
62 |
63 | int idx = 0;
64 | foreach (var s in lst)
65 | {
66 | var cell = row.CreateCell(idx);
67 | double val;
68 | if (double.TryParse(s, out val))
69 | cell.SetCellValue(val);
70 | else
71 | cell.SetCellValue(s);
72 | int curwidth = sheet.GetColumnWidth(idx);
73 | sheet.SetColumnWidth(idx, Math.Max(curwidth, _calcSheetWidth(s)));
74 |
75 | if (row.RowNum == 0)
76 | {
77 | cell.CellStyle = sheet.Workbook.GetCellStyleAt((short)(sheet.Workbook.NumCellStyles - 1));
78 | }
79 |
80 | row.Height = 24 * 15;
81 |
82 | idx++;
83 | }
84 | }
85 |
86 | private static int _calcSheetWidth(string str)
87 | {
88 | var r = 0;
89 | if (str.Length > 50)
90 | str = str.Substring(0, 50);
91 | foreach (var c in str)
92 | {
93 | if ((int)c < 128)
94 | r += 256;
95 | else
96 | r += 512;
97 | }
98 | return Math.Max(2048, r + 1024);
99 | }
100 |
101 | private static void _writeToDefSheet(ISheet sheet, List headers)
102 | {
103 | _writeToSheet(sheet, new string[]
104 | {
105 | "字段名称",
106 | "字段类型",
107 | "字段说明",
108 | });
109 |
110 | foreach (var hdr in headers)
111 | {
112 | _writeToSheet(sheet, new string[]
113 | {
114 | hdr.FieldName,
115 | hdr.FieldType,
116 | hdr.FieldDesc,
117 | });
118 | }
119 | }
120 |
121 | private static void _writeToDataSheet(ISheet sheet, TableExcelData data)
122 | {
123 | var lst = data.Headers.Select(a => a.FieldName).ToList();
124 | _writeToSheet(sheet, lst);
125 |
126 | foreach (var row in data.Rows)
127 | {
128 | _writeToSheet(sheet, row.StrList);
129 | }
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableExportFormat.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace tablegen2.logic
4 | {
5 | public enum TableExportFormat
6 | {
7 | Unknown = 0, //未知
8 | Dat, //加密数据格式
9 | Json, //Json格式
10 | Xml, //Xml格式
11 | Lua, //Lua格式
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/tablegen2/logic/parser/TableGenConfig.cs:
--------------------------------------------------------------------------------
1 | namespace tablegen2.logic
2 | {
3 | public class TableGenConfig
4 | {
5 | public string ExcelDir = string.Empty;
6 | public TableExportFormat ExportFormat = TableExportFormat.Unknown;
7 | public string ExportDir = string.Empty;
8 |
9 | public string SheetNameForField = string.Empty;
10 | public string SheetNameForData = string.Empty;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/tablegen2/packages/ICSharpCode.SharpZipLib.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/tablegen2/packages/ICSharpCode.SharpZipLib.dll
--------------------------------------------------------------------------------
/tablegen2/packages/NPOI.OOXML.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/tablegen2/packages/NPOI.OOXML.dll
--------------------------------------------------------------------------------
/tablegen2/packages/NPOI.OpenXml4Net.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/tablegen2/packages/NPOI.OpenXml4Net.dll
--------------------------------------------------------------------------------
/tablegen2/packages/NPOI.OpenXmlFormats.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/tablegen2/packages/NPOI.OpenXmlFormats.dll
--------------------------------------------------------------------------------
/tablegen2/packages/NPOI.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/tablegen2/packages/NPOI.dll
--------------------------------------------------------------------------------
/tablegen2/packages/Newtonsoft.Json.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/tablegen2/packages/Newtonsoft.Json.dll
--------------------------------------------------------------------------------
/tablegen2/res/excel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monkey256/ExcelExport/4462043b3d0d35143072dafa340a9afa8ecbaada/tablegen2/res/excel.png
--------------------------------------------------------------------------------
/tablegen2/tablegen2.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {4D5AEC09-00D5-41EA-9BE3-67D090C7FCC1}
8 | WinExe
9 | Properties
10 | tablegen2
11 | tablegen2
12 | v4.0
13 | 512
14 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
15 | 4
16 | true
17 |
18 |
19 |
20 | AnyCPU
21 | true
22 | full
23 | false
24 | ..\bin\
25 | DEBUG;TRACE
26 | prompt
27 | 4
28 |
29 |
30 | AnyCPU
31 | pdbonly
32 | true
33 | ..\bin\
34 | TRACE
35 | prompt
36 | 4
37 |
38 |
39 | tablegen2.Program
40 |
41 |
42 | app.ico
43 |
44 |
45 |
46 | packages\Newtonsoft.Json.dll
47 |
48 |
49 | packages\NPOI.dll
50 |
51 |
52 | packages\NPOI.OOXML.dll
53 |
54 |
55 | False
56 | packages\NPOI.OpenXml4Net.dll
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | 4.0
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 | MSBuild:Compile
78 | Designer
79 |
80 |
81 | MSBuild:Compile
82 | Designer
83 |
84 |
85 | MSBuild:Compile
86 | Designer
87 |
88 |
89 | Designer
90 | MSBuild:Compile
91 |
92 |
93 | MSBuild:Compile
94 | Designer
95 |
96 |
97 | MSBuild:Compile
98 | Designer
99 |
100 |
101 | Designer
102 | MSBuild:Compile
103 |
104 |
105 | Designer
106 | MSBuild:Compile
107 |
108 |
109 | Designer
110 | MSBuild:Compile
111 |
112 |
113 | Designer
114 | MSBuild:Compile
115 |
116 |
117 | Designer
118 | MSBuild:Compile
119 |
120 |
121 | Designer
122 | MSBuild:Compile
123 |
124 |
125 | Designer
126 | MSBuild:Compile
127 |
128 |
129 | Designer
130 | MSBuild:Compile
131 |
132 |
133 | Designer
134 | MSBuild:Compile
135 |
136 |
137 | Designer
138 | MSBuild:Compile
139 |
140 |
141 | Designer
142 | MSBuild:Compile
143 |
144 |
145 | Designer
146 | MSBuild:Compile
147 |
148 |
149 | MSBuild:Compile
150 | Designer
151 |
152 |
153 | App.xaml
154 | Code
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 | ButtonDark.xaml
169 |
170 |
171 | ButtonLight.xaml
172 |
173 |
174 | HelperPanel.xaml
175 |
176 |
177 |
178 | PopupWindow.xaml
179 |
180 |
181 | WaitingControl.xaml
182 |
183 |
184 | FrameConsole.xaml
185 |
186 |
187 | FrameExcelView.xaml
188 |
189 |
190 | FrameFileTree.xaml
191 |
192 |
193 | FrameSetting.xaml
194 |
195 |
196 | FrameSettingMore.xaml
197 |
198 |
199 | FrameToolBar.xaml
200 |
201 |
202 | TreeListItem.xaml
203 |
204 |
205 | TreeListView.xaml
206 |
207 |
208 | HeaderFieldEdit.xaml
209 |
210 |
211 | HeaderListItem.xaml
212 |
213 |
214 | HeaderListView.xaml
215 |
216 |
217 | HeaderPage.xaml
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 | MainWindow.xaml
233 | Code
234 |
235 |
236 | MSBuild:Compile
237 | Designer
238 |
239 |
240 |
241 |
242 |
243 | Code
244 |
245 |
246 | True
247 | True
248 | Resources.resx
249 |
250 |
251 | True
252 | Settings.settings
253 | True
254 |
255 |
256 | ResXFileCodeGenerator
257 | Resources.Designer.cs
258 |
259 |
260 | SettingsSingleFileGenerator
261 | Settings.Designer.cs
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
284 |
--------------------------------------------------------------------------------