Example #1
0
     private static void Execute(Options options)
     {
         /* 判断 ExcelPath 为目录路径还是文件路径 */
         string[] excelPaths = null;
         if (Directory.Exists(options.ExcelPath))
         {
             DirectoryInfo dirInfo = new DirectoryInfo(options.ExcelPath);
             excelPaths = dirInfo.GetFiles().Where(fileInfo => ExcelUtil.IsSupported(fileInfo.Name)).Select(fileInfo => fileInfo.FullName).ToArray();
         }
         else if (File.Exists(options.ExcelPath))
         {
             if (ExcelUtil.IsSupported(options.ExcelPath))
             {
                 excelPaths = new[] { options.ExcelPath };
             }
         }
         if (excelPaths == null)
         {
             Console.WriteLine("No supported excel file found.");
             return;
         }
         /* 对目标 Excel 文件进行转译 */
         foreach (var excelPath in excelPaths)
         {
             string excelName = Path.GetFileName(excelPath);
             Console.WriteLine("[{0}]", excelName);
             DataTableCollection dataTables = ExcelReader.ReadExcelToDataTables(excelPath);
             foreach (DataTable dataTable in dataTables)
             {
                 /* 开始转换 DataTable */
                 string sheetName    = dataTable.TableName;
                 int    rowsCount    = dataTable.Rows.Count;
                 int    columnsCount = dataTable.Columns.Count;
                 Console.WriteLine("  sheet {0}(rows: {1}, column: {2})...", sheetName, rowsCount.ToString(), columnsCount.ToString());
                 ESheet sheetType = ExcelUtil.GetSheetType(sheetName);
                 string fileName  = sheetType switch {
                     ESheet.EnumSheet => options.EnumNamePrefix + sheetName.Substring(4),
                     ESheet.ParamSheet => options.ParamNamePrefix + sheetName.Substring(5),
                     ESheet.ClassSheet => options.ClassNamePrefix + sheetName,
                     _ => null
                 };
                 /* 生成 JSON 数据 */
                 Console.WriteLine("    generate json...");
                 string jsonContent = DataWriter.DataTableToJSON(dataTable, options);
                 if (!string.IsNullOrEmpty(jsonContent))
                 {
                     if (!Directory.Exists(options.JSONPath))
                     {
                         Directory.CreateDirectory(options.JSONPath);
                     }
                     string jsonPath = string.Format("{0}/{1}.json", options.JSONPath, fileName);
                     File.WriteAllText(jsonPath, jsonContent, Encoding.UTF8);
                 }
                 /* 生成 C# 代码 */
                 Console.WriteLine("    generate csharp code...");
                 string codeContent = CodeWriter.DataTableToCSharp(dataTable, excelName, options);
                 if (!string.IsNullOrEmpty(codeContent))
                 {
                     if (!Directory.Exists(options.CSharpCodePath))
                     {
                         Directory.CreateDirectory(options.CSharpCodePath);
                     }
                     string codePath = string.Format("{0}/{1}.cs", options.CSharpCodePath, fileName);
                     File.WriteAllText(codePath, codeContent, Encoding.UTF8);
                 }
             }
         }
     }
 }
Example #2
0
        /// <summary> 从 DataTable 生成 C# 代码 </summary>
        public static string DataTableToCSharp(DataTable dataTable, string excelName, Options options)
        {
            if (!CodeUtil.IsValidDataTable(dataTable))
            {
                return(null);
            }
            ESheet        sheetType = ExcelUtil.GetSheetType(dataTable.TableName);
            StringBuilder builder   = new StringBuilder();

            builder.AppendLine("/* Auto generated code */");
            builder.AppendLine();
            switch (sheetType)
            {
            case ESheet.EnumSheet: // 生成枚举类
                string            enumName    = options.EnumNamePrefix + dataTable.TableName.Substring(4);
                List <EnumMember> enumMembers = CodeUtil.GetEnumMembers(dataTable);
                builder.AppendFormat("namespace {0} {{", options.Namespace).AppendLine();
                builder.AppendFormat("    /// <summary> Generate From {0} </summary>", excelName).AppendLine();
                builder.AppendFormat("    public enum {0} {{", enumName).AppendLine();
                // 枚举成员
                foreach (var member in enumMembers)
                {
                    builder.AppendFormat("        /// <summary> {0} </summary>", member.comment).AppendLine();
                    builder.AppendFormat("        {0} = {1},", member.name, member.value).AppendLine();
                }
                builder.AppendLine("    }");
                builder.AppendLine("}");
                break;

            case ESheet.ParamSheet: // 生成参数类
                string            paramName   = options.ParamNamePrefix + dataTable.TableName.Substring(5);
                List <ParamField> paramFields = CodeUtil.GetParamFields(dataTable);
                builder.AppendFormat("namespace {0} {{", options.Namespace).AppendLine();
                builder.AppendFormat("    /// <summary> Generate From {0} </summary>", excelName).AppendLine();
                builder.AppendFormat("    public static class {0} {{", paramName).AppendLine();
                // 静态只读字段
                foreach (var field in paramFields)
                {
                    builder.AppendFormat("        /// <summary> {0} </summary>", field.comment).AppendLine();
                    try {
                        string value = CodeUtil.DataTableValueToCodeForm(field.type, field.value);
                        builder.AppendFormat("        public static readonly {0} {1} = {2};", field.type, field.name, value).AppendLine();
                    } catch (Exception exception) {
                        Console.WriteLine("[Error] Exception at sheet {0}, row: {1}", dataTable.TableName, (paramFields.IndexOf(field) + 1).ToString());
                        Console.WriteLine(exception);
                        throw;
                    }
                }
                builder.AppendLine("    }");
                builder.AppendLine("}");
                break;

            case ESheet.ClassSheet: // 生成数据类
                string            className   = options.ClassNamePrefix + dataTable.TableName;
                List <ClassField> classFields = CodeUtil.GetClassFields(dataTable);
                builder.AppendFormat("namespace {0} {{", options.Namespace).AppendLine();
                builder.AppendFormat("    /// <summary> Generate From {0} </summary>", excelName).AppendLine();
                builder.AppendFormat("    public class {0} {{", className).AppendLine();
                // 字段
                foreach (var field in classFields)
                {
                    builder.AppendFormat("        /// <summary> {0} </summary>", field.comment).AppendLine();
                    builder.AppendFormat("        public readonly {0} {1};", field.type, field.name).AppendLine();
                }
                // 构造函数
                builder.AppendLine();
                builder.AppendFormat("        public {0}(", className)
                .AppendJoin(", ", classFields.Select(field => string.Format("{0} {1}", field.type, field.name)))
                .AppendLine(") {");
                foreach (var field in classFields)
                {
                    builder.AppendFormat("            this.{0} = {0};", field.name).AppendLine();
                }
                builder.AppendLine("        }");
                builder.AppendLine("    }");
                builder.AppendLine("}");
                break;
            }
            builder.AppendLine();
            builder.AppendLine("/* End of auto generated code */");
            return(builder.ToString());
        }