Example #1
0
    public static void MakeCsvClass(string outPaths, string fileCsv,
                                    CsvHeader[] headers, string[] typeStrs)
    {
        string classStr = TemplateClass;

        string headerfile;
        Header typeHeader;

        if (TryGetHeader("_BaseHeader", out typeHeader) && !string.IsNullOrEmpty(typeHeader.path))
        {
            headerfile = typeHeader.path;
        }
        else
        {
            headerfile = string.Empty;
        }

        string        templateSimpe   = TemplateSimpeCase;
        StringBuilder propertyBuilder = new StringBuilder();
        StringBuilder methodBuilder   = new StringBuilder();
        StringBuilder simpleBuilder   = new StringBuilder();
        StringBuilder nodeBuilder     = new StringBuilder();

        string        classKey         = "";
        int           defineFieldIndex = -1;
        List <string> flagKeys         = new List <string>();

        for (int i = 0; i < headers.Length; i++)
        {
            CsvHeader header = headers[i];
            if (header.skip)
            {
                continue;
            }
            bool   isSimple  = false;
            string paramName = string.Empty;
            string fieldName = string.Empty;
            switch (header.type)
            {
            case eFieldType.Primitive:
                fieldName = header.name;
                paramName = "text";
                isSimple  = true;
                break;

            case eFieldType.Array:
                if (flagKeys.Contains(header.baseName))
                {
                    //Debug.Log(file + " Array skip:" + header.name);
                    continue;
                }
                flagKeys.Add(header.baseName);

                fieldName = header.baseName;
                paramName = "node";
                break;

            case eFieldType.Class:
                if (flagKeys.Contains(header.baseName))
                {
                    //Debug.Log(file + " Class skip:" + header.name);
                    continue;
                }
                flagKeys.Add(header.baseName);

                fieldName = header.baseName;
                paramName = "node";
                break;

            default:
                break;
            }

            string typeStr = typeStrs[i];
            if (string.IsNullOrEmpty(typeStr))
            {
                continue;
            }
            if (typeStr == "define")
            {
                defineFieldIndex = i;
                continue;
            }
            if (typeStr[0] == CsvConfig.comment)
            {
                typeStr = typeStr.Substring(1);
            }
            string[] subTypes = typeStr.Split(CsvConfig.classSeparator);
            string   typeName = GetSysType(subTypes[0]);
            subTypes = typeName.Split(CsvConfig.arrayChars);
            typeName = GetSysType(subTypes[0]);
            string baseTypeName = GetSysType(subTypes[0]);
            string funcName     = string.Empty;
            if (subTypes.Length == 1)
            {
                funcName = "Base";
            }
            else
            {
                int arrayNum = (subTypes.Length - 1) / 2;
                for (int num = 0; num < arrayNum; num++)
                {
                    funcName += "Array";
                    typeName  = ComposeTypeName(typeName);
                }
            }

            string template;
            template = templateSimpe.Replace("@funName", funcName).Replace("@name", fieldName)
                       .Replace("@type", initCap(baseTypeName)).Replace("@paramName", paramName);

            if (isSimple)
            {
                simpleBuilder.Append(template);
            }
            else
            {
                nodeBuilder.Append(template);
            }

            if (header.name == CsvConfig.primaryKey)
            {
                classKey = typeName;
                if (classKey == "int")
                {
                    classKey = "Integer";
                }
            }
            propertyBuilder.Append(TemplateProperty.Replace("@type", typeName).Replace("@name", fieldName));
            methodBuilder.Append(TemplateMethod.Replace("@type", typeName).Replace("@name", fieldName).Replace("@MethodName", initCap(fieldName)));
        }

        string fileCsvUpper = fileCsv.Substring(0, 1).ToUpper() + fileCsv.Substring(1);
        string className    = fileCsvUpper + CsvConfig.classPostfix;

        classStr = classStr.Replace("@className", className);
        classStr = classStr.Replace("@classKey", classKey);
        classStr = classStr.Replace("@class", fileCsvUpper);
        classStr = classStr.Replace("@fileName", fileCsv);
        classStr = classStr.Replace("#headerfile#", headerfile);
        classStr = classStr.Replace("#property#", propertyBuilder.ToString());
        classStr = classStr.Replace("#method#", methodBuilder.ToString());
        classStr = classStr.Replace("#BaseCase#", simpleBuilder.ToString());
        classStr = classStr.Replace("#NodeCase#", nodeBuilder.ToString());

        string fileName = className + mSuffixName;

        string[] outPathArrray = outPaths.Split(';');
        foreach (string outPath in outPathArrray)
        {
            if (!Directory.Exists(outPath))
            {
                Directory.CreateDirectory(outPath);
            }
            string filePath = Path.Combine(outPath, fileName);
            File.WriteAllText(filePath, classStr);
            Debug.Log("MakeCsv:" + fileCsv + "\nOutput:" + filePath);

            string raderClassStr  = TemplateReader.Replace("@classname", fileCsvUpper).Replace("@classcsv", className).Replace("@classKey", classKey);
            string readerFileName = fileCsvUpper + "Reader" + mSuffixName;
            string readerFilePath = Path.Combine(outPath, readerFileName);
            File.WriteAllText(readerFilePath, raderClassStr);
        }
    }
Example #2
0
 public PscCsv ComposeCsv(CsvHeader csvHeader, CsvLines CsvLines, CsvFooter csvFooter)
 {
     throw new NotImplementedException();
 }
Example #3
0
    private bool ReadExcel(string filePath, char type, Action headAction, Action <char, IRow> rowAction)
    {
        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
            XSSFWorkbook workbook = new XSSFWorkbook(fs);
            //只读取第一张表
            ISheet sheet = workbook.GetSheetAt(0);
            if (sheet == null)
            {
                Debug.LogError("ReadExcel Error Sheet:" + filePath);
                return(false);
            }
            m_sheetName = sheet.SheetName;

            //第一行为表头,必定是最大列数
            IRow nameRow   = sheet.GetRow(0);
            int  cellCount = nameRow.LastCellNum;
            //表头
            IRow headRow = sheet.GetRow(1);
            //导出类型
            IRow typeRow = sheet.GetRow(2);
            //导出服务器客户端
            IRow exportRow = sheet.GetRow(3);

            ICell cell = exportRow.GetCell(0);
            if (cell == null || cell.StringCellValue == null)
            {
                Debug.LogError("导出配置错误:" + filePath);
                return(false);
            }
            if (cell.StringCellValue != "A" && !cell.StringCellValue.Contains(type))
            {
                Debug.LogWarning("跳过导出:" + filePath);
                return(false);
            }

            //Debug.Log("导出:" + filePath);

            string[] exportSettings = new string[cellCount];
            for (int i = 0; i < cellCount; i++)
            {
                cell = exportRow.GetCell(i);
                if (cell == null)
                {
                    exportSettings[i] = string.Empty;
                    continue;
                }
                exportSettings[i] = cell.StringCellValue;
            }

            m_defineIndex = -1;
            m_rawTypes    = new string[cellCount];
            m_cellTypes   = new string[cellCount];
            //第一列为id,只支持int,string
            cell = typeRow.GetCell(0);
            string value = cell.StringCellValue;
            if (value[0] == CsvConfig.skipFlag)
            {
                m_rawTypes[0]  = value;
                m_cellTypes[0] = value.Substring(1);
            }
            else
            {
                m_rawTypes[0]  = CsvConfig.skipFlag + value;
                m_cellTypes[0] = value;
            }
            for (int i = 1; i < cellCount; i++)
            {
                cell = typeRow.GetCell(i);
                if (cell == null)
                {
                    continue;
                }
                value         = cell.StringCellValue;
                m_rawTypes[i] = value;
                int pos = value.LastIndexOf(CsvConfig.classSeparator);
                if (pos > 0)
                {
                    m_cellTypes[i] = value.Substring(pos + 1);
                }
                else
                {
                    m_cellTypes[i] = value;
                }
            }

            m_headers = new CsvHeader[cellCount];
            for (int i = 0; i < cellCount; i++)
            {
                if (string.IsNullOrEmpty(exportSettings[i]))
                {
                    m_headers[i] = CsvHeader.Pop(string.Empty);
                    continue;
                }
                if (exportSettings[i] != "A" && !exportSettings[i].Contains(type))
                {
                    m_headers[i] = CsvHeader.Pop(string.Empty);
                    continue;
                }

                cell = headRow.GetCell(i);
                if (cell == null)
                {
                    m_headers[i] = CsvHeader.Pop(string.Empty);
                    continue;
                }

                var cellType = m_cellTypes[i];
                if (cellType == "define")
                {
                    m_defineIndex = i;
                    m_defineName  = cell.StringCellValue;
                    m_headers[i]  = CsvHeader.Pop(string.Empty);
                    continue;
                }

                m_headers[i] = CsvHeader.Pop(cell.StringCellValue);
                if (m_headers[i].type == eFieldType.Array && cellType.Length > 2 &&
                    cellType.EndsWith("[]", StringComparison.OrdinalIgnoreCase) &&
                    m_headers[i].name == m_headers[i].baseName)
                {
                    //去除结尾的[]
                    m_cellTypes[i] = cellType.Substring(0, cellType.Length - 2);
                }
            }
            int            slot;
            List <string>  nodeSlots = new List <string>(1);
            List <CsvNode> nodes     = new List <CsvNode>(1);
            for (int i = 0; i < m_headers.Length; i++)
            {
                CsvHeader header = m_headers[i];
                if (header.type == eFieldType.Primitive)
                {
                    header.SetSlot(-1);
                    continue;
                }
                slot = nodeSlots.IndexOf(header.baseName);
                if (slot < 0)
                {
                    nodeSlots.Add(header.baseName);
                    header.SetSlot(nodeSlots.Count - 1);
                    var node     = CsvNode.Pop(header.baseName, header.type);
                    var subTypes = m_rawTypes[i].Split(CsvConfig.arrayChars, CsvConfig.classSeparator);
                    node.cellType = subTypes[0];
                    nodes.Add(node);
                }
                else
                {
                    header.SetSlot(slot);
                }
            }
            if (nodeSlots.Count > 0)
            {
                m_nodes = nodes.ToArray();
            }
            else
            {
                m_nodes = new CsvNode[0];
            }

            headAction();

            m_rawIds.Clear();
            int startIndex = 4;// sheet.FirstRowNum;
            int lastIndex  = sheet.LastRowNum;
            for (int index = startIndex; index <= lastIndex; index++)
            {
                m_curIndex = index;
                IRow row = sheet.GetRow(index);
                if (row == null)
                {
                    continue;
                }

                //跳过id为空,或者#号开头的行
                cell = row.GetCell(0);
                if (cell == null)
                {
                    continue;
                }
                var obj = getCellValue(cell);
                if (obj == null)
                {
                    continue;
                }
                string id = obj.ToString();
                if (string.IsNullOrEmpty(id) || id[0] == CsvConfig.skipFlag)
                {
                    continue;
                }

                if (m_rawIds.IndexOf(id) >= 0)
                {
                    Debug.LogError(m_filePath + " 重复id, index:" + index + " id:" + id);
                    continue;
                }
                m_rawIds.Add(id);

                try {
                    rowAction(type, row);
                }
                catch (Exception e) {
                    Debug.LogError(m_filePath + " 转换错误, index:" + index + " info:" + obj + " \n" + e);
                }
            }
        }
        return(true);
    }
Example #4
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="header">We ref this simply for performance reasons.</param>
        /// <param name="memberName"></param>
        /// <param name="type"></param>
        /// <param name="classType"></param>
        private static void GetTypeFromHeader(ref CsvHeader header, ref string memberName, out Type type, out string classType)
        {
            classType = "";

            if (memberName.Contains("("))
            {

                // The user is defining the type for this property
                classType = CsvHeader.GetClassNameFromHeader(header.Name);

                bool shouldBeNewed = false;

                if (classType.StartsWith("List<"))
                {
                    classType = "System.Collections.Generic." + classType;
                    shouldBeNewed = true;
                }

                if (string.IsNullOrEmpty(classType))
                {
                    // We can get here if the class is (required)
                    type = typeof(string);
                }
                else
                {
                    if (classType.Contains("<"))
                    {
                        ParsedType parsedType = new ParsedType(classType);
                        type = TypeManager.GetTypeFromParsedType(parsedType);
                    }
                    else
                    {
                        type = TypeManager.GetTypeFromString(classType);
                    }
                }

                memberName = StringFunctions.RemoveWhitespace(memberName);

                memberName = memberName.Substring(0, memberName.IndexOfAny(new char[] { '(' }));

                if (shouldBeNewed)
                {
                    // The user probably wants these new'ed:
                    memberName += " = new " + classType + "()";
                }
            }
            else
            {
                memberName = StringFunctions.RemoveWhitespace(memberName);
                type = typeof(string);
            }
        }
Example #5
0
        public void FromTypeWithAliasTest()
        {
            var header = CsvHeader.FromType <Person2>();

            Assert.AreEqual(CsvHeader.FromValues("first_name", "age"), header);
        }
Example #6
0
        public void FromTypeTest()
        {
            var header = CsvHeader.FromType <Person1>();

            Assert.AreEqual(CsvHeader.FromValues("Name", "Age"), header);
        }
Example #7
0
        public void EqualsTest()
        {
            var header = new CsvHeader(new string[] { "id", "name", "age" });

            Assert.AreEqual(CsvHeader.FromValues("id", "name", "age"), header);
        }
Example #8
0
        public void ToStringTest()
        {
            var header = new CsvHeader(new string[] { "id", "name", "age" });

            Assert.AreEqual("id,name,age", header.ToString());
        }
    public static void MakeCsvClass(string outPaths, string fileCsv,
                                    CsvHeader[] headers, string[] typeStrs,
                                    string headExtend, string csvExtend, string readerExtend)
    {
        //string fileCsv = Path.GetFileNameWithoutExtension(file);
        string classStr = TemplateCsv;

        string headerfile;
        Header typeHeader;

        if (TryGetHeader("_BaseHeader", out typeHeader) && !string.IsNullOrEmpty(typeHeader.path))
        {
            headerfile = typeHeader.path;
        }
        else
        {
            headerfile = string.Empty;
        }
        if (!string.IsNullOrEmpty(headExtend))
        {
            headerfile += headExtend;
        }

        StringBuilder propertyBuilder = new StringBuilder();
        StringBuilder simpleBuilder   = new StringBuilder();
        StringBuilder nodeBuilder     = new StringBuilder();

        List <string> flagKeys   = new List <string>();
        List <string> importKeys = new List <string>();

        for (int i = 0; i < headers.Length; i++)
        {
            CsvHeader header = headers[i];
            if (header.skip)
            {
                continue;
            }
            bool   isSimple  = false;
            string fieldName = string.Empty;
            string paramName = string.Empty;
            bool   isEnum    = false;
            switch (header.type)
            {
            case eFieldType.Primitive:
                fieldName = header.name;
                paramName = "Text";
                isSimple  = true;
                break;

            case eFieldType.Array:
                if (flagKeys.Contains(header.baseName))
                {
                    //Debug.Log(file + " Array skip:" + header.name);
                    continue;
                }
                flagKeys.Add(header.baseName);

                fieldName = header.baseName;
                paramName = "Node";
                break;

            case eFieldType.Class:
                if (flagKeys.Contains(header.baseName))
                {
                    //Debug.Log(file + " Class skip:" + header.name);
                    continue;
                }
                flagKeys.Add(header.baseName);

                fieldName = header.baseName;
                paramName = "Node";
                break;

            default:
                break;
            }

            string typeStr = typeStrs[i];
            if (string.IsNullOrEmpty(typeStr))
            {
                continue;
            }
            if (typeStr == "define")
            {
                //define文件生成标志
                continue;
            }
            if (typeStr[0] == CsvConfig.comment)
            {
                typeStr = typeStr.Substring(1);
            }
            string[] subTypes = typeStr.Split(CsvConfig.classSeparator);
            string   typeName = GetSysType(subTypes[0]);
            subTypes = subTypes[0].Split(CsvConfig.arrayChars);
            string baseTypeName = GetConvertType(subTypes[0]);
            string funcName     = string.Empty;
            if (subTypes.Length == 1)
            {
                funcName = "Base";
            }
            else
            {
                int arrayNum = (subTypes.Length - 1) / 2;
                for (int num = 0; num < arrayNum; num++)
                {
                    funcName += "Array";
                }
            }

            if (TryGetHeader(baseTypeName, out typeHeader))
            {
                isEnum = typeHeader.isEnum;
                if (!string.IsNullOrEmpty(typeHeader.path) && !importKeys.Contains(baseTypeName))
                {
                    headerfile += typeHeader.path;
                    importKeys.Add(baseTypeName);
                }
            }

            string template;
            if (isEnum)
            {
                template = TemplateCsvCase_Enum.Replace("@funName", funcName).Replace("@name", fieldName)
                           .Replace("@type", baseTypeName)
                           .Replace("@paramName", paramName)
                           .Replace("@lowerParamName", paramName.ToLower());
            }
            else
            {
                template = TemplateCsvCase_Simple.Replace("@funName", funcName).Replace("@name", fieldName)
                           .Replace("@type", baseTypeName)
                           .Replace("@paramName", paramName)
                           .Replace("@lowerParamName", paramName.ToLower());
            }

            if (isSimple)
            {
                simpleBuilder.Append(template);
            }
            else
            {
                nodeBuilder.Append(template);
            }

            template = TemplateCsvProperty.Replace("@type", typeName).Replace("@name", fieldName);
            propertyBuilder.Append(template);
        }

        string fileCsvUpper = fileCsv.Substring(0, 1).ToUpper() + fileCsv.Substring(1);
        string className    = fileCsvUpper + CsvConfig.classPostfix;

        classStr = classStr.Replace("@className", fileCsvUpper);
        //classStr = classStr.Replace("@class", fileCsvUpper);
        classStr = classStr.Replace("@fileName", fileCsv);
        classStr = classStr.Replace("#headerfile#", headerfile);
        classStr = classStr.Replace("#property#", propertyBuilder.ToString());
        classStr = classStr.Replace("#BaseCase#", simpleBuilder.ToString());
        classStr = classStr.Replace("#NodeCase#", nodeBuilder.ToString());
        classStr = classStr.Replace("#extendCsv#", csvExtend);
        classStr = classStr.Replace("#extendReader#", readerExtend);

        classStr = Regex.Replace(classStr, "(?<!\r)\n|\r\n", "\n");

        string fileName = className + mSuffixName;

        string[] outPathArrray = outPaths.Split(';');
        foreach (string outPath in outPathArrray)
        {
            if (!Directory.Exists(outPath))
            {
                Directory.CreateDirectory(outPath);
            }
            string filePath = Path.Combine(outPath, fileName);
            File.WriteAllText(filePath, classStr);
            Debug.Log("MakeCsv:" + fileCsv + "\nOutput:" + filePath);
        }
    }