Example #1
0
        public string BuildConfig(string wszInputFilePath, string wszDefaultNamespace, string dllpath)
        {
            EnumConver = new StringBuilder();
            var tables = getTableName(wszInputFilePath);
            var fi     = new FileInfo(wszInputFilePath);
            var config = new List <string>(tables).Find(r => r.ToLower() == "@@config" || r == "Sheet2$" || r == "Sheet2");

            var           headmapdic = CsvCodeBuilder.GetTypeNameMapDefine(wszInputFilePath, dllpath);
            StringBuilder sb         = new StringBuilder();

            sb.AppendLine("namespace {0} {".Replace("{0}", wszDefaultNamespace));
            if (config != null)
            {
                var ds = importExcelToDataSet(wszInputFilePath, config).Tables[0];
                for (int i = 0; i < ds.Columns.Count; i++)
                {
                    var colum = ds.Columns[i];
                    if (!string.IsNullOrEmpty(colum.ColumnName) && !colum.ColumnName.StartsWith("Column"))
                    {
                        ;

                        List <string> Configs   = new List <string>();
                        List <string> EnConfigs = new List <string>();
                        var           finame    = fi.Name.Replace(fi.Extension, "");

                        for (int j = 0; j < ds.Rows.Count; j++)
                        {
                            var data = ds.Rows[j][i] + "";
                            if (!string.IsNullOrEmpty(data))
                            {
                                Configs.Add(data);
                                var head = CsvCodeBuilder.HeadFix(data);


                                if (headmapdic.ContainsKey(finame + "." + head))
                                {
                                    head = headmapdic[finame + "." + head];
                                }
                                else if (headmapdic.ContainsKey(head))
                                {
                                    head = headmapdic[head];
                                }
                                else
                                {
                                    if (headmapdic.ContainsKey("#srcurl") && headmapdic.ContainsKey("#dstmath"))
                                    {
                                        head = CsvCodeBuilder.GetTranslateByUrl(
                                            headmapdic["#srcurl"],
                                            headmapdic["#dstmath"],
                                            head,
                                            wszInputFilePath
                                            );
                                    }
                                }
                                EnConfigs.Add(head);
                            }
                        }

                        //buid
                        var classname = FixRowName(colum.ColumnName);


                        if (headmapdic.ContainsKey(finame + "." + classname))
                        {
                            classname = headmapdic[finame + "." + classname];
                        }
                        else if (headmapdic.ContainsKey(classname))
                        {
                            classname = headmapdic[classname];
                        }
                        else
                        {
                            if (headmapdic.ContainsKey("#srcurl") && headmapdic.ContainsKey("#dstmath"))
                            {
                                classname = CsvCodeBuilder.GetTranslateByUrl(
                                    headmapdic["#srcurl"],
                                    headmapdic["#dstmath"],
                                    classname,
                                    wszInputFilePath
                                    );
                            }
                        }
                        sb.AppendLine(@"
        /// <summary>
        /// {oldhead}
        /// </summary>".Replace("{oldhead}", colum.ColumnName));
                        //添加枚举映射
                        EnumMap[colum.ColumnName] = classname;
                        var classtxt = @"public enum Enum_{class}{";
                        sb.AppendLine(classtxt.Replace("{class}", classname));


                        var bodytpl = @" 
case ""{head}"":
      return Enum_{class}.{new};
                        ";
                        var body    = new StringBuilder();
                        for (int j = 0; j < Configs.Count; j++)
                        {
                            var oldhead = Configs[j];
                            var newhead = EnConfigs[j];
                            sb.AppendLine(@"
        /// <summary>
        /// {oldhead}
        /// </summary>".Replace("{oldhead}", oldhead));
                            sb.AppendLine(newhead + ",");

                            body.AppendLine(bodytpl
                                            .Replace("{head}", oldhead)
                                            .Replace("{new}", newhead)
                                            .Replace("{class}", classname)
                                            );
                        }

                        EnumConver.AppendLine(@"
                    ExctionClass.RegEnumConvert<Enum_{class}>(o =>
                    {
                        var str = o.ToString();
                        switch (str)
                        {
                            {body}
                        }
                        return Enum_{class}.{0};
                });
                "
                                              .Replace("{class}", classname)
                                              .Replace("{body}", body.ToString())
                                              .Replace("{0}", EnConfigs[0])

                                              );

                        {
                            var bodytplback = @" 
case Enum_{class}.{new}:
      return ""{head}"";
                        ";
                            var bodyback    = new StringBuilder();
                            for (int j = 0; j < Configs.Count; j++)
                            {
                                var oldhead = Configs[j];
                                var newhead = EnConfigs[j];

                                bodyback.AppendLine(bodytplback
                                                    .Replace("{head}", oldhead)
                                                    .Replace("{new}", newhead)
                                                    .Replace("{class}", classname)
                                                    );
                            }

                            EnumConver.AppendLine(@"
                    ExctionClass.RegEnumConvertBack<Enum_{class}>(o =>
                    {
                        var str = (Enum_{class})o;
                        switch (str)
                        {
                            {body}
                        }
                        return """";
                });
                "
                                                  .Replace("{class}", classname)
                                                  .Replace("{body}", bodyback.ToString())
                                                  .Replace("{0}", EnConfigs[0])

                                                  );
                        }

                        sb.AppendLine("}");
                    }
                }
            }

            sb.AppendLine("}");
            return(sb.ToString());
        }
Example #2
0
        public override void GenerateOnFile(StringBuilder codes, string wszInputFilePath, string bstrInputFileContents,
                                            string wszDefaultNamespace, string dllpath)
        {
            codes.AppendLine("//Code Gen By ExcelCodeBuilder V1.3 ...");
            codes.AppendLine("//Addin path " + dllpath);
            codes.AppendLine(@"
using System;
using System.Collections.Generic;
using System.Xml;
");
            var tables = getTableName(wszInputFilePath);

            //先创建枚举类型
            var eunmstr = BuildConfig(wszInputFilePath, wszDefaultNamespace, dllpath);

            codes.AppendLine(eunmstr);
            codes.AppendLine("//eunms Gen By ExcelCodeBuilder  ...");

            int tabindex = -1;

            foreach (var table in tables)
            {
                tabindex++;
                var ds = importExcelToDataSet(wszInputFilePath, table).Tables[0];
                if (table.StartsWith("@@") || table.StartsWith("__"))
                {
                    //不导出此类表
                    continue;
                }

                var fileInfo = new FileInfo(wszInputFilePath);

                if (!File.Exists(fileInfo.Directory.FullName + "//ConfigHelper.cs"))
                {
                    var cspath = new FileInfo(dllpath).Directory.FullName + "//Tpl//ConfigHelper.cs";

                    if (File.Exists(cspath))
                    {
                        File.Copy(cspath, fileInfo.Directory.FullName + "//ConfigHelper.cs", true);
                    }
                }
                var classname = fileInfo.Name.Replace(fileInfo.Extension, "");

                string        key      = null;
                StringBuilder body     = new StringBuilder();
                StringBuilder method   = new StringBuilder();
                StringBuilder setbody  = new StringBuilder();
                StringBuilder igetbody = new StringBuilder();
                StringBuilder isetbody = new StringBuilder();
                if (table != "Sheet1$" && table != "Sheet1")
                {
                    classname = table;
                }
                classname = CsvCodeBuilder.HeadFix(classname);
                string oldclassname = classname;
                var    headmapdic   = CsvCodeBuilder.GetTypeNameMapDefine(wszInputFilePath, dllpath);

                if (headmapdic.ContainsKey(classname))
                {
                    classname = headmapdic[classname];
                }
                else
                {
                    if (headmapdic.ContainsKey("#srcurl") && headmapdic.ContainsKey("#dstmath"))
                    {
                        classname = CsvCodeBuilder.GetTranslateByUrl(
                            headmapdic["#srcurl"],
                            headmapdic["#dstmath"],
                            classname,
                            wszInputFilePath
                            );
                    }
                }

                if (headmapdic.ContainsKey("#xmlout"))
                {
                    var path = fileInfo.Directory.FullName + headmapdic["#xmlout"];
                    path = new FileInfo(path).FullName + "\\";
                    codes.AppendLine("//xmlout " + path);

                    path += classname;
                    MyConvertExcelToXml(wszInputFilePath, path, table);
                }

                //if (!classname.EndsWith("Table"))
                //{
                //    classname = classname + "Table";
                //}
                //建立主体
                {
                    var dic = CsvCodeBuilder.GetTypeDefine(wszInputFilePath, dllpath);



                    string args   = "";
                    string IDHead = "ID";
                    for (int i = 0; i < ds.Columns.Count; i++)
                    {
                        string head    = ds.Columns[i].ColumnName;
                        string oldhead = head;
                        if (head.StartsWith("@@")) //直接截断
                        {
                            break;
                        }

                        if (head.StartsWith("__")) //忽略
                        {
                            continue;
                        }

                        if (head.StartsWith("_"))//移除下划线
                        {
                            head = head.Substring(1);
                        }
                        if (head.StartsWith("__"))//移除下划线
                        {
                            head = head.Substring(2);
                        }
                        if (head == "")
                        {
                            head = "h" + i;
                        }

                        string type = "string";


                        type = ds.Columns[i].DataType.Name;

                        if (type == "Double")
                        {
                            type = "int";
                        }


                        head = CsvCodeBuilder.HeadFix(head);



                        if (dic.ContainsKey(classname + "." + head))
                        {
                            type = dic[classname + "." + head];
                        }
                        else if (dic.ContainsKey(head))
                        {
                            type = dic[head];
                        }

                        if (headmapdic.ContainsKey(classname + "." + head))
                        {
                            head = headmapdic[classname + "." + head];
                        }
                        else if (headmapdic.ContainsKey(head))
                        {
                            head = headmapdic[head];
                        }
                        else
                        {
                            if (headmapdic.ContainsKey("#srcurl") && headmapdic.ContainsKey("#dstmath"))
                            {
                                head = CsvCodeBuilder.GetTranslateByUrl(
                                    headmapdic["#srcurl"],
                                    headmapdic["#dstmath"],
                                    head,
                                    wszInputFilePath
                                    );
                            }
                        }

                        if (i == 0)
                        {
                            IDHead = head;
                        }


                        if (key == null)
                        {
                            key = type;
                        }

                        if (type == "枚举" || type == "enum")
                        {
                            if (EnumMap.ContainsKey(ds.Columns[i].ColumnName))
                            {
                                type = "Enum_" + EnumMap[ds.Columns[i].ColumnName];
                            }
                        }

                        setbody.AppendLine("case \"{0}\":".Replace("{0}", ds.Columns[i].ColumnName));

                        var fixRowName = FixRowName(ds.Columns[i].ColumnName);
                        if (fixRowName != ds.Columns[i].ColumnName)
                        {
                            setbody.AppendLine("case \"{0}\":".Replace("{0}", fixRowName));
                        }

                        //setbody.AppendLine("this._" + head + " =new Func<" + type +  ">(()=> { return  ConfigHelper.ConvertTo<" + type + ">(localnode.InnerText); });");
                        setbody.AppendLine("this._" + head + " =   ConfigHelper.ConvertTo<" + type + ">(localnode.InnerText); ");

                        setbody.AppendLine("break;");

                        body.AppendLine(@"
        /// <summary>
        /// {oldhead}
        /// </summary>".Replace("{oldhead}", oldhead)
                                        );

                        //if (i == 0)
                        //    body.AppendLine("\t\t[Config(Index = 0, IsKey = true, Desc = \"" + ds.Columns[i].ColumnName + "\")]");
                        //else
                        //    body.AppendLine("\t\t[Config(Index = " + i + " , Desc = \"" + ds.Columns[i].ColumnName + "\")]");

                        body.AppendLine(@"
 //ConfigValue<{0}> _{1} ;
{0} _{1};

/// <summary>
/// {oldhead}
/// </summary>
[ConfigItemMap(""{oldhead}"")]
public {0} {1} { 
    get{
       return _{1};
}
  set {
    _{1} = value;
}
    
}

"
                                        .Replace("{0}", type)
                                        .Replace("{1}", head)
                                        .Replace("{oldhead}", oldhead)

                                        );

                        igetbody.Append(@"
if (memberName == '{1}')
{
    return {1};
}
".Replace('\'', '\"')
                                        .Replace("{1}", head)

                                        );

                        isetbody.Append(@"
 if (memberName == '{1}')
{
    obj.{1} = ({0})newValue;
}
".Replace('\'', '\"')
                                        .Replace("{1}", head)
                                        .Replace("{0}", type)
                                        );


                        if (args != "")
                        {
                            args += ",";
                        }
                        args += type + " " + head;
                    }



                    method.AppendLine(
                        @"
#if !RELEASE_CLIENT
        string xmldata = null;

        public override string ToString()
        {
            return xmldata;
        }
#endif
        /// <summary>
        /// ID
        /// </summary>
        //public string xmlcrc { get;set; }

        public bool CheckId()
        {
            if ({ID} > 0)
            {
                return true;
            }
            return false;
        }


        public int GetId()
       {
            return   ConfigHelper.ConvertTo<int>({ID});
        }
        public void Parse(XmlNode xmlnode)
        {
#if !RELEASE_CLIENT
                 xmldata = xmlnode.InnerXml;
#endif
                //xmlcrc = xmlnode.InnerXml.GetHashCode().ToString();
                foreach(XmlNode node in xmlnode)
                {
                    var localnode = node;
                    switch(node.Name)
                    {
                        {body}
                    }
                }
        }


"
                        .Replace("{body}", setbody.ToString())
                        .Replace("{ID}", IDHead)

                        );


                    body.AppendLine(method.ToString());
                }


                //建立类
                codes.AppendLine(@"

namespace {0} 
{
    /// <summary>
    /// {oldclass}
    /// </summary>
    [Serializable]
    //[Config(Index = {index})]
    public partial class {1} 
#if MA
       :IMemberAccessor
#endif
    {

{body}
        public object GetValue(object instance, string memberName)
        {
            {getbody}
            return null;
        }

        public void SetValue(object instance, string memberName, object newValue)
        {
             var obj = instance as {1};
            {setbody}
        }
    }

    
  
    

"
                                 .Replace("{0}", wszDefaultNamespace)
                                 .Replace("{1}", classname)
                                 .Replace("{body}", body.ToString())
                                 .Replace("{getbody}", igetbody.ToString())
                                 .Replace("{setbody}", isetbody.ToString())
                                 .Replace("{ext}", "\"" + Exction + "\"")
                                 .Replace("{oldclass}", oldclassname)
                                 .Replace("{index}", tabindex.ToString())

                                 );

                BuildConfigReadClass(codes, classname, oldclassname);

                codes.AppendLine("}");
                if (table == "Sheet1$" || table == "Sheet1")
                {
                    break;
                }
            }
        }
Example #3
0
        public static void MyConvertExcelToXmlI(string excelFilePath, string xmlOutFileDic, string tablename)
        {
            var names      = getTableName(excelFilePath);
            var dic        = new FileInfo(excelFilePath).Directory.FullName;
            var headmapdic = new Dictionary <string, string>();

            try
            {
                Console.WriteLine(dic + "//nameMap.txt");
                headmapdic = CsvCodeBuilder.GetTypeNameMapDefine(dic + "//nameMap.txt", "./");
            }
            catch (Exception)
            {
            }

            var dump = false;

            foreach (var name in names)
            {
                if (tablename == name || tablename == null)
                {
                    if (tablename == null && name.StartsWith("@@"))
                    {
                        break;
                    }
                    if (name.StartsWith("_"))
                    {
                        continue;
                    }

                    var classname = CsvCodeBuilder.HeadFix(new FileInfo(excelFilePath).Name.Replace(".xlsx", ""));

                    if (name != "Sheet1")
                    {
                        classname = CsvCodeBuilder.HeadFix(name);
                    }
                    else
                    {
                        dump = true;
                    }
                    if (headmapdic.ContainsKey(classname))
                    {
                        classname = headmapdic[classname];
                    }

                    var ds         = importExcelToDataSet(excelFilePath, name, true);
                    var ds2        = importExcelToDataSet(excelFilePath, name, false);
                    var table      = ds.Tables[0];
                    var table2     = ds2.Tables[0];
                    var removeName = new List <string>();
                    foreach (DataColumn column in table.Columns)
                    {
                        if (column.ColumnName.StartsWith("_"))
                        {
                            removeName.Add(column.ColumnName);
                        }
                    }

                    foreach (var colName in removeName)
                    {
                        table.Columns.Remove(colName);
                        table2.Columns.Remove(colName);
                    }

                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        DataRow row = table.Rows[i];
                        for (int j = 0; j < row.ItemArray.Length; j++)
                        {
                            var value = row[j];
                            if (value.ToString() == "")
                            {
                                if (table2.Columns[j].DataType == typeof(string) ||
                                    table2.Columns[j].DataType == typeof(DateTime))
                                {
                                    row[j] = "";
                                }
                                else
                                {
                                    row[j] = 0;
                                }
                            }
                        }
                    }


                    if (xmlOutFileDic.EndsWith("\\"))
                    {
                        ds.WriteXml(xmlOutFileDic + classname + ".xml");
                        ds.Dispose();
                        Console.WriteLine(xmlOutFileDic + classname + ".xml");
                    }
                    else
                    {
                        ds.WriteXml(xmlOutFileDic + ".xml");
                        ds.Dispose();
                        Console.WriteLine(xmlOutFileDic + ".xml");
                    }

                    if (dump)
                    {
                        break;
                    }
                }
            }
        }