├── _ExempleExcel ├── Include Enum │ ├── Enum.xlsx │ └── Example_With_Enum.xlsx ├── Not Include Enum │ └── Example_Without_Enum.xlsx └── Multiple Sheets │ └── Example_Multiple_Sheets.xlsx ├── ExcelToJsonWizard ├── ExcelToJsonWizard │ ├── ExcelToJsonWizard.csproj │ └── Program.cs ├── ExcelToJsonWizard.sln └── .gitignore ├── LICENSE ├── README.md ├── README_kr.md └── .gitignore /_ExempleExcel/Include Enum/Enum.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/npckero/ExcelToJsonWizard/HEAD/_ExempleExcel/Include Enum/Enum.xlsx -------------------------------------------------------------------------------- /_ExempleExcel/Include Enum/Example_With_Enum.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/npckero/ExcelToJsonWizard/HEAD/_ExempleExcel/Include Enum/Example_With_Enum.xlsx -------------------------------------------------------------------------------- /_ExempleExcel/Not Include Enum/Example_Without_Enum.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/npckero/ExcelToJsonWizard/HEAD/_ExempleExcel/Not Include Enum/Example_Without_Enum.xlsx -------------------------------------------------------------------------------- /_ExempleExcel/Multiple Sheets/Example_Multiple_Sheets.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/npckero/ExcelToJsonWizard/HEAD/_ExempleExcel/Multiple Sheets/Example_Multiple_Sheets.xlsx -------------------------------------------------------------------------------- /ExcelToJsonWizard/ExcelToJsonWizard/ExcelToJsonWizard.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 npckero 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ExcelToJsonWizard/ExcelToJsonWizard.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34322.80 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExcelToJsonWizard", "ExcelToJsonWizard\ExcelToJsonWizard.csproj", "{52F35B1C-171A-45C2-A53B-13A3658647FD}" 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 | {52F35B1C-171A-45C2-A53B-13A3658647FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {52F35B1C-171A-45C2-A53B-13A3658647FD}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {52F35B1C-171A-45C2-A53B-13A3658647FD}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {52F35B1C-171A-45C2-A53B-13A3658647FD}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {EE0CB064-74F6-46B1-B300-4A556FD78B66} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExcelToJsonWizard 2 | A tool for converting Excel data to JSON files and generating C# loader classes for use in Unity. 3 | 4 | # JSON Converter Tool 5 | 6 | This tool converts Excel files to JSON files and generates corresponding C# loader classes. The tool is configured using a `config.txt` file and supports various options, including handling multiple sheets and using Unity's Resources folder for JSON file loading. 7 | 8 | ## Features 9 | - Converts Excel files to JSON files. 10 | - Generates C# loader classes for the JSON files. 11 | - Supports Enum definitions from a separate `Enum.xlsx` file. 12 | - Configurable via a `config.txt` file. 13 | - Handles multiple sheets in Excel files. 14 | - Supports Unity's `Resources` folder for loading JSON files. 15 | 16 | ## Prerequisites 17 | - .NET Core or .NET Framework installed. 18 | - ClosedXML library for reading Excel files. 19 | 20 | ## Installation 21 | 1. Clone the repository. 22 | 2. Open the solution in your preferred IDE. 23 | 3. Restore NuGet packages. 24 | 25 | ## Configuration 26 | The tool uses a `config.txt` file for configuration. The `config.txt` file and necessary directories will be automatically generated on the first run. 27 | 28 | ## Usage 29 | 1. **Prepare your Excel files**: 30 | - Place your Excel files in the directory specified in `config.txt`. 31 | - Ensure your Excel files are formatted correctly (see below). 32 | 33 | 2. **Run the tool**: 34 | - Execute the compiled program. 35 | - The tool will read the Excel files, generate JSON files and C# loader classes, and save them in the specified directories. 36 | 37 | ## Excel File Format 38 | - The first row should contain variable names. 39 | - The second row should contain data types. 40 | - The third row should contain descriptions (optional, but "No description provided." will be used if empty). 41 | - The fourth row and beyond should contain the data. 42 | 43 | ## Enum Definitions 44 | - Enum definitions should be placed in the first sheet of `Enum.xlsx`. 45 | - The first row should contain the Enum name. 46 | - The second column onwards should contain the Enum values. 47 | - Enum definitions are used from the first row onwards without a header row. 48 | - If Enum definitions are not needed, there is no need to create the `Enum.xlsx` file. 49 | 50 | ## Possible Errors and Troubleshooting 51 | 1. **Missing `key` column**: 52 | - Ensure the first column in your Excel file is named `key`. 53 | 54 | 2. **Incorrect data type**: 55 | - Ensure the data type specified in the second row is correct and supported (e.g., `int`, `string`, `List`, etc.). 56 | 57 | 3. **Duplicate `key` values**: 58 | - Ensure that there are no duplicate values in the `key` column. 59 | 60 | 4. **Enum type not found**: 61 | - Ensure the `Enum.xlsx` file exists and is formatted correctly. 62 | - Ensure the Enum name in the Excel file matches the name in `Enum.xlsx`. 63 | 64 | 5. **Resource loading issues**: 65 | - If using Unity's `Resources.Load`, ensure the path is correct and the file exists in the Resources folder. 66 | -------------------------------------------------------------------------------- /README_kr.md: -------------------------------------------------------------------------------- 1 | # JSON 변환 도구 2 | 3 | 이 도구는 엑셀 파일을 JSON 파일로 변환하고 해당 JSON 파일을 로드할 수 있는 C# 로더 클래스를 생성합니다. `config.txt` 파일을 통해 다양한 옵션을 설정할 수 있으며, Enum 정의도 처리합니다. 4 | 5 | ## 주요 기능 6 | - 엑셀 파일을 JSON 파일로 변환 7 | - JSON 파일을 로드할 수 있는 C# 로더 클래스 생성 8 | - 별도의 `Enum.xlsx` 파일을 통해 Enum 정의 지원 9 | - `config.txt` 파일을 통해 설정 가능 10 | - 다중 시트 처리 지원 11 | - Unity의 `Resources` 폴더를 사용할 수 있는 옵션 제공 12 | 13 | ## 사전 준비 14 | - .NET Core 또는 .NET Framework 설치 15 | - ClosedXML 라이브러리 설치 (엑셀 파일 읽기용) 16 | 17 | ## 설치 방법 18 | 1. 저장소를 클론합니다. 19 | 2. 선호하는 IDE에서 솔루션을 엽니다. 20 | 3. NuGet 패키지를 복원합니다. 21 | 22 | ## 설정 23 | 이 도구는 `config.txt` 파일을 사용하여 설정을 관리합니다. `config.txt` 파일과 필요한 디렉토리는 처음 실행 시 자동으로 생성됩니다. 24 | 25 | ## 사용 방법 26 | 1. **엑셀 파일 준비**: 27 | - 엑셀 파일을 `config.txt`에 지정된 디렉토리에 넣습니다. 28 | - 엑셀 파일의 형식이 올바른지 확인합니다 (아래 참조). 29 | 30 | 2. **도구 실행**: 31 | - 컴파일된 프로그램을 실행합니다. 32 | - 도구는 엑셀 파일을 읽고 JSON 파일과 C# 로더 클래스를 생성하여 지정된 디렉토리에 저장합니다. 33 | 34 | ## 엑셀 파일 형식 35 | - 첫 번째 행은 변수 이름을 포함해야 합니다. 36 | - 두 번째 행은 데이터 타입을 포함해야 합니다. 37 | - 세 번째 행은 설명을 포함해야 합니다 (선택 사항, 비어 있을 경우 "No description provided."가 사용됩니다). 38 | - 네 번째 행부터는 데이터가 포함됩니다. 39 | 40 | ## Enum 정의 41 | - Enum 정의는 별도의 `Enum.xlsx` 파일을 통해 처리됩니다. 42 | - `Enum.xlsx` 파일의 첫 번째 시트를 사용합니다. 43 | - 첫 번째 행은 Enum 이름을 포함해야 하며, 두 번째 열부터는 Enum 값을 포함해야 합니다. 44 | - Enum 정의는 설명 줄 없이 첫 번째 행부터 바로 사용됩니다. 45 | - Enum 정의가 필요하지 않다면 `Enum.xlsx` 파일을 만들 필요가 없습니다. 46 | 47 | ## 발생할 수 있는 오류 및 해결 방법 48 | 1. **`key` 열 누락**: 49 | - 엑셀 파일의 첫 번째 열이 `key`인지 확인하십시오. 50 | 51 | 2. **잘못된 데이터 타입**: 52 | - 두 번째 행에 지정된 데이터 타입이 올바르고 지원되는지 확인하십시오 (예: `int`, `string`, `List` 등). 53 | 54 | 3. **중복된 `key` 값**: 55 | - `key` 열에 중복된 값이 없는지 확인하십시오. 56 | 57 | 4. **Enum 타입을 찾을 수 없음**: 58 | - `Enum.xlsx` 파일이 존재하고 올바르게 형식화되었는지 확인하십시오. 59 | - 엑셀 파일의 Enum 이름이 `Enum.xlsx`의 이름과 일치하는지 확인하십시오. 60 | 61 | 5. **Resource 로딩 문제**: 62 | - Unity의 `Resources.Load`를 사용하는 경우 경로가 정확하고 파일이 Resources 폴더에 존재하는지 확인하십시오. 63 | 64 | 65 | ## 활용 방법 66 | 1. 유니티 Resources 폴더 사용할 때 설정법 67 | Unity의 Resources 폴더를 사용하여 JSON 파일을 로드하려면 config.txt 파일에서 useResources 옵션을 true로 설정하고, resourcesInternalPath를 설정합니다. 68 | 69 | 다음 단계를 따르십시오: 70 | 71 | 1. config.txt 파일을 엽니다. 72 | 2. 다음 항목을 설정합니다: 73 | - useResources=true 74 | - resourcesInternalPath에 JSON 파일이 저장될 Resources 폴더 내의 경로를 설정합니다. 예를 들어, resourcesInternalPath=Data/JsonFiles라고 설정하면 Resources/Data/JsonFiles 경로를 사용하게 됩니다. 75 | 3. 엑셀 파일을 변환하여 JSON 파일을 생성합니다. 76 | 4. 생성된 JSON 파일을 Unity 프로젝트의 Resources 폴더 내의 설정된 경로에 복사합니다. 77 | 78 | json 파일 생성 경로를 미리 Resources 폴더에 연결해두면 바로사용 가능 합니다. 79 | 80 | 2. 멀티 시트 사용할 때 설정법 81 | 엑셀 파일에 여러 시트가 있는 경우, 각 시트를 변환하려면 config.txt 파일에서 allowMultipleSheets 옵션을 true로 설정합니다. 82 | 83 | 다음 단계를 따르십시오: 84 | 85 | 1. config.txt 파일을 엽니다. 86 | 2. 다음 항목을 설정합니다: 87 | - allowMultipleSheets=true 88 | 3. 엑셀 파일을 준비합니다. 각 시트는 서로 다른 데이터 구조를 가질 수 있습니다. 89 | 4. 도구를 실행하여 JSON 파일과 C# 로더 클래스를 생성합니다. 각 시트에 대해 별도의 JSON 파일과 로더 클래스가 생성됩니다. 90 | 91 | 예를 들어, Example_Multiple_Sheets.xlsx 파일이 있고 Sheet1과 Sheet2가 있다면, 다음과 같은 파일들이 생성됩니다: 92 | 93 | - Example_Multiple_Sheets_Sheet1.json 94 | - Example_Multiple_Sheets_Sheet2.json 95 | - Example_Multiple_Sheets_Sheet1Loader.cs 96 | - Example_Multiple_Sheets_Sheet2Loader.cs 97 | 이렇게 생성된 파일들을 사용하여 다양한 시트 데이터를 처리할 수 있습니다. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /ExcelToJsonWizard/.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /ExcelToJsonWizard/ExcelToJsonWizard/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using ClosedXML.Excel; 7 | using System.Text.Json; 8 | using System.Text.Encodings.Web; 9 | using System.Text.Unicode; 10 | 11 | namespace ExcelToJsonWizard 12 | { 13 | class Program 14 | { 15 | static Dictionary> enumMappings; 16 | static bool emptyValueDetectedInFile = false; // 빈 값이 감지되었는지 여부를 추적하는 변수 17 | 18 | static void Main() 19 | { 20 | // 실행 파일의 현재 디렉토리 가져오기 21 | string basePath = AppDomain.CurrentDomain.BaseDirectory; 22 | // 설정 파일을 실행 파일 위치에서 찾도록 수정 23 | string configFilePath = Path.Combine(basePath, "config.txt"); 24 | var config = LoadConfiguration(configFilePath); 25 | 26 | 27 | string defaultExcelDirectoryPath = "excel_files"; 28 | string defaultLoaderOutputDirectory = "loader_output"; 29 | string defaultJsonOutputDirectory = "json_output"; 30 | 31 | bool useAbsolutePath = config.ContainsKey("useAbsolutePath") && config["useAbsolutePath"].ToLower() == "true"; 32 | bool allowMultipleSheets = config.ContainsKey("allowMultipleSheets") && config["allowMultipleSheets"].ToLower() == "true"; 33 | bool useResources = config.ContainsKey("useResources") && config["useResources"].ToLower() == "true"; 34 | string resourcesInternalPath = config.ContainsKey("resourcesInternalPath") ? config["resourcesInternalPath"] : "default/path"; 35 | 36 | string excelDirectoryPath = ValidateOrCreateDirectory(config, "excelDirectoryPath", defaultExcelDirectoryPath, useAbsolutePath, basePath); 37 | string loaderOutputDirectory = ValidateOrCreateDirectory(config, "loaderOutputDirectory", defaultLoaderOutputDirectory,useAbsolutePath, basePath); 38 | string jsonOutputDirectory = ValidateOrCreateDirectory(config, "jsonOutputDirectory", defaultJsonOutputDirectory, useAbsolutePath, basePath); 39 | string logFilePath = Path.Combine("log", $"{DateTime.Now:yyyy-MM-dd}_error_log.txt"); 40 | 41 | if (!Directory.Exists("log")) 42 | { 43 | Directory.CreateDirectory("log"); 44 | } 45 | 46 | // Load Enum definitions and generate Enum C# file 47 | enumMappings = LoadEnumDefinitionsAndGenerateCs(excelDirectoryPath, loaderOutputDirectory, logFilePath); 48 | 49 | ProcessExcelFiles(excelDirectoryPath, loaderOutputDirectory, jsonOutputDirectory, logFilePath, allowMultipleSheets, useResources, resourcesInternalPath); 50 | 51 | // 프로그램 완료 후 콘솔 창을 유지합니다. 52 | Console.WriteLine("Press any key to exit..."); 53 | Console.ReadLine(); 54 | } 55 | 56 | static Dictionary LoadConfiguration(string configFilePath) 57 | { 58 | var config = new Dictionary(); 59 | 60 | if (File.Exists(configFilePath)) 61 | { 62 | var lines = File.ReadAllLines(configFilePath); 63 | foreach (var line in lines) 64 | { 65 | if (string.IsNullOrWhiteSpace(line) || line.TrimStart().StartsWith("#")) 66 | { 67 | continue; // 주석이거나 빈 줄은 무시 68 | } 69 | 70 | var cleanLine = line.Split('#')[0].Trim(); // 주석 부분을 제거하고 정리 71 | var parts = cleanLine.Split(new[] { '=' }, 2); 72 | if (parts.Length == 2) 73 | { 74 | config[parts[0].Trim()] = parts[1].Trim(); 75 | } 76 | } 77 | } 78 | else 79 | { 80 | using (var sw = File.CreateText(configFilePath)) 81 | { 82 | sw.WriteLine("# 사용자 지정 디렉토리 설정"); 83 | sw.WriteLine("excelDirectoryPath=excel_files # 엑셀 파일 디렉토리 경로"); 84 | sw.WriteLine("loaderOutputDirectory=loader_output # 로더 클래스 출력 디렉토리 경로"); 85 | sw.WriteLine("jsonOutputDirectory=json_output # JSON 파일 출력 디렉토리 경로"); 86 | sw.WriteLine(); 87 | 88 | sw.WriteLine("# 경로 타입 선택"); 89 | sw.WriteLine("useAbsolutePath = false # 절대 경로를 사용할지 여부 (true: 절대 경로, false: 실행 파일 기준 상대 경로)"); 90 | sw.WriteLine(); 91 | 92 | sw.WriteLine("# 다중 시트 설정"); 93 | sw.WriteLine("allowMultipleSheets=false # 다중 시트를 허용할지 여부 (true/false)"); 94 | sw.WriteLine(); 95 | 96 | sw.WriteLine("# Resources 사용 설정"); 97 | sw.WriteLine("useResources=true # Resources 폴더 사용 여부 (true/false)"); 98 | sw.WriteLine("resourcesInternalPath=JSON # Resources 내부 경로"); 99 | } 100 | 101 | config["excelDirectoryPath"] = "excel_files"; 102 | config["loaderOutputDirectory"] = "loader_output"; 103 | config["jsonOutputDirectory"] = "json_output"; 104 | config["useAbsolutePath"] = "false"; 105 | config["allowMultipleSheets"] = "false"; 106 | config["useResources"] = "true"; 107 | config["resourcesInternalPath"] = "JSON"; 108 | } 109 | 110 | return config; 111 | } 112 | 113 | static string ValidateOrCreateDirectory(Dictionary config, string key, string defaultDirectory, bool useAbsolutePath, string basePath) 114 | { 115 | string path; 116 | if (config.ContainsKey(key)) 117 | { 118 | path = config[key]; 119 | 120 | // 상대 경로 사용 옵션이 꺼져 있다면 실행 파일 경로를 기준으로 변환 121 | if (!useAbsolutePath && !Path.IsPathRooted(path)) 122 | { 123 | path = Path.Combine(basePath, path); 124 | } 125 | } 126 | else 127 | { 128 | path = Path.Combine(basePath, defaultDirectory); 129 | } 130 | 131 | if (!Directory.Exists(path)) 132 | { 133 | Directory.CreateDirectory(path); 134 | Console.WriteLine($"Created directory: {path}"); 135 | } 136 | return path; 137 | } 138 | 139 | static Dictionary> LoadEnumDefinitionsAndGenerateCs(string excelDir, string loaderDir, string logFilePath) 140 | { 141 | var enumDefinitions = new Dictionary>(); 142 | var enumFilePath = Path.Combine(excelDir, "Enum.xlsx"); 143 | 144 | if (File.Exists(enumFilePath)) 145 | { 146 | try 147 | { 148 | var sb = new StringBuilder(); 149 | sb.AppendLine("using System;"); 150 | sb.AppendLine(); 151 | sb.AppendLine("public static class DesignEnums"); 152 | sb.AppendLine("{"); 153 | 154 | using (var workbook = new XLWorkbook(enumFilePath)) 155 | { 156 | var worksheet = workbook.Worksheet(1); 157 | 158 | foreach (var row in worksheet.RowsUsed()) 159 | { 160 | var enumName = row.Cell(1).GetValue(); 161 | if (enumDefinitions.ContainsKey(enumName)) 162 | { 163 | throw new Exception($"Duplicate enum name '{enumName}' found in Enum definitions."); 164 | } 165 | 166 | var enumValues = new Dictionary(); 167 | int index = 0; 168 | 169 | sb.AppendLine($" public enum {enumName}"); 170 | sb.AppendLine(" {"); 171 | 172 | for (int col = 2; col <= row.LastCellUsed().Address.ColumnNumber; col++) 173 | { 174 | var value = row.Cell(col).GetValue(); 175 | if (enumValues.ContainsKey(value)) 176 | { 177 | throw new Exception($"Duplicate value '{value}' found in enum '{enumName}'."); 178 | } 179 | 180 | enumValues[value] = index; 181 | sb.AppendLine($" {value} = {index},"); 182 | index++; 183 | } 184 | 185 | sb.AppendLine(" }"); 186 | enumDefinitions[enumName] = enumValues; 187 | } 188 | } 189 | 190 | sb.AppendLine("}"); 191 | 192 | var enumOutputPath = Path.Combine(loaderDir, "DesignEnums.cs"); 193 | File.WriteAllText(enumOutputPath, sb.ToString()); 194 | Console.WriteLine($"Enum definitions file generated\n"); 195 | } 196 | catch (Exception ex) 197 | { 198 | LogError(logFilePath, $"Error loading Enum definitions from file {enumFilePath}: {ex.Message}\n{ex.StackTrace}"); 199 | Console.WriteLine($"Error loading Enum definitions from file {enumFilePath}: {ex.Message}"); 200 | } 201 | } 202 | 203 | return enumDefinitions; 204 | } 205 | 206 | static void ProcessExcelFiles(string excelDir, string loaderDir, string jsonDir, string logFilePath, bool allowMultipleSheets, bool useResources, string resourcesInternalPath) 207 | { 208 | var excelFiles = Directory.GetFiles(excelDir, "*.xlsx"); 209 | 210 | int totalFiles = excelFiles.Length; 211 | int errorFiles = 0; 212 | int processedFiles = 0; 213 | 214 | foreach (var excelFilePath in excelFiles) 215 | { 216 | if (Path.GetFileName(excelFilePath).StartsWith("~") || Path.GetFileName(excelFilePath).Equals("Enum.xlsx", StringComparison.OrdinalIgnoreCase)) 217 | { 218 | Console.WriteLine($"Skipping file: {excelFilePath}\n"); 219 | continue; 220 | } 221 | 222 | bool success = GenerateClassAndJsonFromExcel(excelFilePath, loaderDir, jsonDir, logFilePath, allowMultipleSheets, useResources, resourcesInternalPath); 223 | if (success) 224 | { 225 | processedFiles++; 226 | } 227 | else 228 | { 229 | errorFiles++; 230 | } 231 | } 232 | 233 | Console.WriteLine($"Total files processed: {totalFiles}"); 234 | Console.WriteLine($"Successfully processed files: {processedFiles}"); 235 | Console.WriteLine($"Files with errors: {errorFiles}"); 236 | } 237 | 238 | static bool GenerateClassAndJsonFromExcel(string excelPath, string loaderDir, string jsonDir, string logFilePath, bool allowMultipleSheets, bool useResources, string resourcesInternalPath) 239 | { 240 | try 241 | { 242 | emptyValueDetectedInFile = false; // 새로운 파일을 처리할 때마다 초기화 243 | 244 | using (var workbook = new XLWorkbook(excelPath)) 245 | { 246 | IEnumerable sheets = allowMultipleSheets ? workbook.Worksheets : new[] { workbook.Worksheet(1) }; 247 | 248 | foreach (var worksheet in sheets) 249 | { 250 | try 251 | { 252 | var rows = worksheet.RowsUsed(); 253 | 254 | if (!rows.Any()) 255 | { 256 | continue; 257 | } 258 | 259 | var className = allowMultipleSheets ? 260 | MakeValidClassName($"{Path.GetFileNameWithoutExtension(excelPath)}_{worksheet.Name}") : 261 | MakeValidClassName(Path.GetFileNameWithoutExtension(excelPath)); 262 | var sb = new StringBuilder(); 263 | 264 | sb.AppendLine("using System;"); 265 | sb.AppendLine("using System.Collections.Generic;"); 266 | sb.AppendLine("using System.IO;"); 267 | sb.AppendLine("using UnityEngine;"); 268 | sb.AppendLine(); 269 | sb.AppendLine($"[Serializable]"); 270 | sb.AppendLine($"public class {className}"); 271 | sb.AppendLine("{"); 272 | 273 | var headers = worksheet.Row(1).Cells(); 274 | var types = worksheet.Row(2).Cells(); 275 | var descriptions = worksheet.Row(3).Cells(); 276 | 277 | int validColumnCount = 0; 278 | for (int i = 0; i < headers.Count(); i++) 279 | { 280 | string header = headers.ElementAt(i).GetString(); 281 | string type = types.ElementAt(i).GetString(); 282 | 283 | // 빈 셀이 하나라도 나오면 중단 284 | if (string.IsNullOrWhiteSpace(header) || string.IsNullOrWhiteSpace(type)) 285 | { 286 | break; 287 | } 288 | 289 | validColumnCount++; 290 | } 291 | 292 | if (!headers.ElementAt(0).GetString().Equals("key", StringComparison.OrdinalIgnoreCase)) 293 | { 294 | throw new Exception("The first column must be 'key'."); 295 | } 296 | 297 | if (!types.ElementAt(0).GetString().Equals("int", StringComparison.OrdinalIgnoreCase)) 298 | { 299 | throw new Exception("The type of the first column must be 'int'."); 300 | } 301 | 302 | for (int i = 0; i < validColumnCount; i++) 303 | { 304 | var variableName = headers.ElementAt(i).GetString(); 305 | var dataType = types.ElementAt(i).GetString(); 306 | var description = descriptions.ElementAtOrDefault(i)?.GetString() ?? "No description provided."; 307 | 308 | if ((dataType.StartsWith("Enum<") || dataType.StartsWith("List"; 331 | } 332 | 333 | sb.AppendLine($" /// "); 334 | sb.AppendLine($" /// {description}"); 335 | sb.AppendLine($" /// "); 336 | sb.AppendLine($" public {dataType} {variableName};"); 337 | sb.AppendLine(); 338 | } 339 | 340 | sb.AppendLine("}"); 341 | 342 | sb.AppendLine($"public class {className}Loader"); 343 | sb.AppendLine("{"); 344 | sb.AppendLine($" public List<{className}> ItemsList {{ get; private set; }}"); 345 | sb.AppendLine($" public Dictionary ItemsDict {{ get; private set; }}"); 346 | sb.AppendLine(); 347 | if (useResources) 348 | { 349 | sb.AppendLine($" public {className}Loader(string path = \"{resourcesInternalPath}/{className}\")"); 350 | } 351 | else 352 | { 353 | sb.AppendLine($" public {className}Loader(string path)"); 354 | } 355 | sb.AppendLine(" {"); 356 | sb.AppendLine(" string jsonData;"); 357 | if (useResources) 358 | { 359 | sb.AppendLine(" jsonData = Resources.Load(path).text;"); 360 | } 361 | else 362 | { 363 | sb.AppendLine(" jsonData = File.ReadAllText(path);"); 364 | } 365 | sb.AppendLine(" ItemsList = JsonUtility.FromJson(jsonData).Items;"); 366 | sb.AppendLine($" ItemsDict = new Dictionary();"); 367 | sb.AppendLine(" foreach (var item in ItemsList)"); 368 | sb.AppendLine(" {"); 369 | sb.AppendLine($" ItemsDict.Add(item.key, item);"); 370 | sb.AppendLine(" }"); 371 | sb.AppendLine(" }"); 372 | sb.AppendLine(); 373 | sb.AppendLine($" [Serializable]"); 374 | sb.AppendLine($" private class Wrapper"); 375 | sb.AppendLine(" {"); 376 | sb.AppendLine($" public List<{className}> Items;"); 377 | sb.AppendLine(" }"); 378 | sb.AppendLine(); 379 | 380 | // GetByKey 메서드 추가 381 | sb.AppendLine($" public {className} GetByKey(int key)"); 382 | sb.AppendLine(" {"); 383 | sb.AppendLine(" if (ItemsDict.ContainsKey(key))"); 384 | sb.AppendLine(" {"); 385 | sb.AppendLine(" return ItemsDict[key];"); 386 | sb.AppendLine(" }"); 387 | sb.AppendLine(" return null;"); 388 | sb.AppendLine(" }"); 389 | 390 | // GetByIndex 메서드 추가 391 | sb.AppendLine($" public {className} GetByIndex(int index)"); 392 | sb.AppendLine(" {"); 393 | sb.AppendLine(" if (index >= 0 && index < ItemsList.Count)"); 394 | sb.AppendLine(" {"); 395 | sb.AppendLine(" return ItemsList[index];"); 396 | sb.AppendLine(" }"); 397 | sb.AppendLine(" return null;"); 398 | sb.AppendLine(" }"); 399 | sb.AppendLine("}"); 400 | 401 | var jsonArray = new List>(); 402 | var keySet = new HashSet(); 403 | 404 | 405 | 406 | for (int i = 4; i <= worksheet.LastRowUsed().RowNumber(); i++) 407 | { 408 | var row = worksheet.Row(i); 409 | var rowDict = new Dictionary(); 410 | 411 | for (int j = 0; j < validColumnCount; j++) 412 | { 413 | var variableName = headers.ElementAt(j).GetString(); 414 | var dataType = types.ElementAt(j).GetString(); 415 | var cellValue = row.Cell(j + 1).GetValue(); 416 | 417 | 418 | 419 | var convertedValue = ConvertToType(cellValue, dataType, variableName, logFilePath, excelPath, worksheet.Name); 420 | 421 | if (variableName == "key" && !keySet.Add((int)convertedValue)) 422 | { 423 | throw new Exception($"Duplicate key value '{convertedValue}' found in sheet '{worksheet.Name}' of file '{excelPath}'"); 424 | } 425 | 426 | rowDict[variableName] = convertedValue; 427 | } 428 | 429 | jsonArray.Add(rowDict); 430 | } 431 | 432 | var classCode = sb.ToString(); 433 | var loaderOutputPath = Path.Combine(loaderDir, $"{className}.cs"); 434 | File.WriteAllText(loaderOutputPath, classCode); 435 | Console.WriteLine($"Class file generated at {className}"); 436 | 437 | var jsonOutputPath = Path.Combine(jsonDir, $"{className}.json"); 438 | var wrapper = new { Items = jsonArray }; 439 | var jsonData = JsonSerializer.Serialize(wrapper, new JsonSerializerOptions 440 | { 441 | WriteIndented = true, 442 | Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) 443 | }); 444 | File.WriteAllText(jsonOutputPath, jsonData); 445 | Console.WriteLine($"JSON file generated at {className}\n"); 446 | 447 | // 파일 처리 후, 빈 값이 감지되었을 때 메시지 출력 448 | if (emptyValueDetectedInFile) 449 | { 450 | Console.WriteLine($"Warning: Empty values detected in file '{excelPath}'. Default values were used."); 451 | LogError(logFilePath, $"Empty values detected in file '{excelPath}'. Default values were used."); 452 | } 453 | } 454 | catch (Exception ex) 455 | { 456 | LogError(logFilePath, $"Error processing sheet {worksheet.Name} in file {excelPath}: {ex.Message}\n{ex.StackTrace}"); 457 | Console.WriteLine($"Error processing sheet {worksheet.Name} in file {excelPath}: {ex.Message}"); 458 | return false; 459 | } 460 | } 461 | } 462 | return true; 463 | } 464 | catch (Exception ex) 465 | { 466 | LogError(logFilePath, $"Error processing file {excelPath}: {ex.Message}\n{ex.StackTrace}"); 467 | Console.WriteLine($"Error processing file {excelPath}: {ex.Message}"); 468 | return false; 469 | } 470 | } 471 | 472 | static object ConvertToType(string value, string type, string variableName, string logFilePath, string excelPath, string sheetName) 473 | { 474 | try 475 | { 476 | // 빈 칸일 경우 기본값 설정 477 | if (string.IsNullOrWhiteSpace(value)) 478 | { 479 | // 파일 내에서 처음으로 빈 칸이 발견되면 플래그 설정 480 | if (!emptyValueDetectedInFile) 481 | { 482 | emptyValueDetectedInFile = true; 483 | } 484 | 485 | // 리스트 타입에서 빈 칸을 허용하지 않도록 메시지 출력 486 | if (type.StartsWith("List<")) 487 | { 488 | throw new Exception($"Empty values are not supported for list types. Variable '{variableName}' in sheet '{sheetName}' of file '{excelPath}' contains an empty value."); 489 | } 490 | 491 | // Enum 타입에서 빈 칸을 허용하지 않도록 메시지 출력 492 | if (type.StartsWith("Enum<")) 493 | { 494 | throw new Exception($"Empty values are not supported for Enum types. Variable '{variableName}' in sheet '{sheetName}' of file '{excelPath}' contains an empty value."); 495 | } 496 | 497 | // 타입에 따른 기본값 처리 498 | switch (type) 499 | { 500 | case "int": 501 | return 0; // 기본값 0 502 | case "float": 503 | return 0.0f; // 기본값 0.0f 504 | case "double": 505 | return 0.0; // 기본값 0.0 506 | case "bool": 507 | return false; // 기본값 false 508 | case "string": 509 | return ""; // 기본값 빈 문자열 510 | default: 511 | throw new Exception($"Unsupported data type: {type}"); 512 | } 513 | } 514 | 515 | if (type.StartsWith("List enumMap[v.Trim()]).ToList(); 524 | } 525 | else if (type.StartsWith("List<")) 526 | { 527 | var itemType = type.Substring(5, type.Length - 6); 528 | if (itemType == "int") 529 | { 530 | return value.Split(',').Select(int.Parse).ToList(); 531 | } 532 | else if (itemType == "float") 533 | { 534 | return value.Split(',').Select(float.Parse).ToList(); 535 | } 536 | else if (itemType == "double") 537 | { 538 | return value.Split(',').Select(double.Parse).ToList(); 539 | } 540 | else if (itemType == "bool") 541 | { 542 | return value.Split(',').Select(bool.Parse).ToList(); 543 | } 544 | else 545 | { 546 | return value.Split(',').Select(v => v.Trim()).ToList(); 547 | } 548 | } 549 | else if (type == "int") 550 | { 551 | return int.Parse(value); 552 | } 553 | else if (type == "float") 554 | { 555 | return float.Parse(value); 556 | } 557 | else if (type == "double") 558 | { 559 | return double.Parse(value); 560 | } 561 | else if (type == "bool") 562 | { 563 | return bool.Parse(value); 564 | } 565 | else if (type.StartsWith("Enum<")) 566 | { 567 | var enumTypeName = type.Substring(5, type.Length - 6); 568 | if (!enumMappings.ContainsKey(enumTypeName)) 569 | { 570 | throw new Exception($"Enum type '{enumTypeName}' not found in Enum definitions."); 571 | } 572 | var enumMap = enumMappings[enumTypeName]; 573 | return enumMap[value]; 574 | } 575 | else if (type == "string") 576 | { 577 | return value; 578 | } 579 | else 580 | { 581 | throw new Exception($"Unsupported data type: {type}"); 582 | } 583 | } 584 | catch (Exception ex) 585 | { 586 | LogError(logFilePath, $"Error converting value '{value}' for variable '{variableName}' in sheet '{sheetName}' of file '{excelPath}': {ex.Message}\n{ex.StackTrace}"); 587 | throw; 588 | } 589 | } 590 | 591 | static string MakeValidClassName(string name) 592 | { 593 | var sb = new StringBuilder(); 594 | foreach (var c in name) 595 | { 596 | if (char.IsLetterOrDigit(c) || c == '_') 597 | { 598 | sb.Append(c); 599 | } 600 | } 601 | 602 | return sb.ToString(); 603 | } 604 | 605 | static void LogError(string logFilePath, string message) 606 | { 607 | try 608 | { 609 | using (StreamWriter sw = File.AppendText(logFilePath)) 610 | { 611 | sw.WriteLine($"{DateTime.Now}: {message}"); 612 | } 613 | } 614 | catch (Exception ex) 615 | { 616 | Console.WriteLine($"Failed to write to log file: {ex.Message}"); 617 | } 618 | } 619 | } 620 | } 621 | --------------------------------------------------------------------------------