/// <summary>
        /// Cell 값을 원하는 Type으로 변환하는 함수
        /// </summary>
        /// <param name="_cell"></param>
        /// <param name="_type"></param>
        /// <returns></returns>
        object ConvertFrom(ICell _cell, Type _type)
        {
            object _value = null;

            if (_cell.CellType == NPOI.SS.UserModel.CellType.Blank)
            {
                return(_value);
            }

            if (_type == typeof(byte) || _type == typeof(float) || _type == typeof(double) || _type == typeof(short) || _type == typeof(int) || _type == typeof(long))
            {
                if (_cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    _value = _cell.NumericCellValue;
                }
                else if (_cell.CellType == NPOI.SS.UserModel.CellType.String)
                {
                    if (_type == typeof(byte))
                    {
                        byte _parseValue = 0;
                        if (byte.TryParse(_cell.StringCellValue, out _parseValue) == false)
                        {
                            UnityEngine.Debug.LogErrorFormat("ExcelLoader Error : 잘못된 타입의 값이 들어가있습니다. 시트={0}, 행={1}, 열={2},", _cell.Sheet.SheetName, _cell.RowIndex, _cell.ColumnIndex);
                        }
                        _value = _parseValue;
                    }
                    else if (_type == typeof(float))
                    {
                        float _parseValue = 0;
                        if (float.TryParse(_cell.StringCellValue, out _parseValue) == false)
                        {
                            UnityEngine.Debug.LogErrorFormat("ExcelLoader Error : 잘못된 타입의 값이 들어가있습니다. 시트={0}, 행={1}, 열={2},", _cell.Sheet.SheetName, _cell.RowIndex, _cell.ColumnIndex);
                        }
                        _value = _parseValue;
                    }
                    else if (_type == typeof(double))
                    {
                        double _parseValue = 0;
                        if (double.TryParse(_cell.StringCellValue, out _parseValue) == false)
                        {
                            UnityEngine.Debug.LogErrorFormat("ExcelLoader Error : 잘못된 타입의 값이 들어가있습니다. 시트={0}, 행={1}, 열={2},", _cell.Sheet.SheetName, _cell.RowIndex, _cell.ColumnIndex);
                        }
                        _value = _parseValue;
                    }
                    else if (_type == typeof(short))
                    {
                        short _parseValue = 0;
                        if (short.TryParse(_cell.StringCellValue, out _parseValue) == false)
                        {
                            UnityEngine.Debug.LogErrorFormat("ExcelLoader Error : 잘못된 타입의 값이 들어가있습니다. 시트={0}, 행={1}, 열={2},", _cell.Sheet.SheetName, _cell.RowIndex, _cell.ColumnIndex);
                        }
                        _value = _parseValue;
                    }
                    else if (_type == typeof(int))
                    {
                        int _parseValue = 0;
                        if (int.TryParse(_cell.StringCellValue, out _parseValue) == false)
                        {
                            UnityEngine.Debug.LogErrorFormat("ExcelLoader Error : 잘못된 타입의 값이 들어가있습니다. 시트={0}, 행={1}, 열={2},", _cell.Sheet.SheetName, _cell.RowIndex, _cell.ColumnIndex);
                        }
                        _value = _parseValue;
                    }
                    else if (_type == typeof(long))
                    {
                        long _parseValue = 0;
                        if (long.TryParse(_cell.StringCellValue, out _parseValue) == false)
                        {
                            UnityEngine.Debug.LogErrorFormat("ExcelLoader Error : 잘못된 타입의 값이 들어가있습니다. 시트={0}, 행={1}, 열={2},", _cell.Sheet.SheetName, _cell.RowIndex, _cell.ColumnIndex);
                        }
                        _value = _parseValue;
                    }
                }
                else if (_cell.CellType == NPOI.SS.UserModel.CellType.Formula)
                {
                    if (_type == typeof(float))
                    {
                        _value = Convert.ToSingle(_cell.NumericCellValue);
                    }
                    if (_type == typeof(double))
                    {
                        _value = Convert.ToDouble(_cell.NumericCellValue);
                    }
                    if (_type == typeof(short))
                    {
                        _value = Convert.ToInt16(_cell.NumericCellValue);
                    }
                    if (_type == typeof(int))
                    {
                        _value = Convert.ToInt32(_cell.NumericCellValue);
                    }
                    if (_type == typeof(long))
                    {
                        _value = Convert.ToInt64(_cell.NumericCellValue);
                    }
                }
            }
            else if (_type == typeof(string) || _type.IsArray)
            {
                if (_cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    _value = _cell.NumericCellValue;
                }
                else
                {
                    _value = _cell.StringCellValue;
                }
            }
            else if (_type == typeof(bool))
            {
                try
                {
                    _value = _cell.BooleanCellValue;
                }
                catch (Exception e)
                {
                    bool temp;
                    if (Boolean.TryParse(_cell.StringCellValue, out temp))
                    {
                        _value = temp;
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
            else if (_type.IsGenericType && _type.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                var nc = new NullableConverter(_type);
                return(nc.ConvertFrom(_value));
            }
            else if (_type.IsEnum)
            {
                if (_cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    int _intValue = 0;
                    if (Int32.TryParse(_cell.NumericCellValue.ToString(), out _intValue) == false)
                    {
                        UnityEngine.Debug.LogError("ExcelLoader Error : Enum타입이 잘못 기입되어있습니다.");
                    }
                    else
                    {
                        _value = Enum.ToObject(_type, _intValue);
                    }
                }
                else
                {
                    _value = Enum.Parse(_type, _cell.StringCellValue, true);
                }
                return(_value);
            }

            if (_type.IsArray)
            {
                if (_type.GetElementType() == typeof(float))
                {
                    return(ConvertToArray <float>((string)_value));
                }
                else if (_type.GetElementType() == typeof(double))
                {
                    return(ConvertToArray <double>((string)_value));
                }
                else if (_type.GetElementType() == typeof(short))
                {
                    return(ConvertToArray <short>((string)_value));
                }
                else if (_type.GetElementType() == typeof(int))
                {
                    return(ConvertToArray <int>((string)_value));
                }
                else if (_type.GetElementType() == typeof(long))
                {
                    return(ConvertToArray <long>((string)_value));
                }
                else if (_type.GetElementType() == typeof(string))
                {
                    return(ConvertToArray <string>((string)_value));
                }
            }

            return(Convert.ChangeType(_value, _type));
        }
예제 #2
0
        /// <summary>
        /// 将动态类型转为指定类型实体
        /// </summary>
        /// <param name="data"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static object DynamicToEntity(ExpandoObject data, Type type)
        {
            var entity = Activator.CreateInstance(type);

            var dic = data as IDictionary <string, object>;

            foreach (var item in dic)
            {
                if (item.Value == null)
                {
                    continue;
                }

                var type_value = item.Value.GetType();

                if (type_value == typeof(DBNull))
                {
                    continue;
                }

                var prop = type.GetProperty(item.Key, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);

                if (prop == null)
                {
                    continue;
                }

                object value = item.Value;

                if (type_value != prop.PropertyType)
                {
                    if (type_value == typeof(List <object>))
                    {
                        var valueList    = Activator.CreateInstance(prop.PropertyType);
                        var dicValueList = value as List <object>;

                        foreach (var valueItem in dicValueList)
                        {
                            prop.PropertyType.GetMethod("Add")
                            .Invoke(valueList, new object[] {
                                DynamicToEntity(valueItem as ExpandoObject, prop.PropertyType.GenericTypeArguments[0])
                            });
                        }

                        value = valueList;
                    }
                    else if (type_value == typeof(ExpandoObject))
                    {
                        value = DynamicToEntity(item.Value as ExpandoObject, prop.PropertyType);
                    }
                    else if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                    {
                        NullableConverter newNullableConverter = new NullableConverter(prop.PropertyType);
                        try
                        {
                            if (!newNullableConverter.CanConvertFrom(item.Value.GetType()))
                            {
                                value = Convert.ChangeType(item.Value, newNullableConverter.UnderlyingType);
                            }
                            else
                            {
                                value = newNullableConverter.ConvertFrom(item.Value);
                            }
                        }
#pragma warning disable CA1031 // Do not catch general exception types
                        catch
                        {
                            value = newNullableConverter.ConvertFromString(item.Value?.ToString());
                        }
#pragma warning restore CA1031 // Do not catch general exception types
                    }
                    else
                    {
                        value = Convert.ChangeType(item.Value, prop.PropertyType);
                    }
                }
                prop.SetValue(entity, value);
            }
            return(entity);
        }
예제 #3
0
        /// <summary>
        /// Convert type of cell value to its predefined type which is specified in the sheet's ScriptMachine setting file.
        /// </summary>
        protected object ConvertFrom(ICell cell, Type t)
        {
            object value = null;

            if (t == typeof(uint) || t == typeof(float) || t == typeof(double) || t == typeof(short) || t == typeof(int) || t == typeof(long))
            {
                if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    value = cell.NumericCellValue;
                }
                else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                {
                    //Get correct numeric value even the cell is string type but defined with a numeric type in a data class.
                    if (t == typeof(float))
                    {
                        value = Convert.ToSingle(cell.StringCellValue);
                    }
                    if (t == typeof(double))
                    {
                        value = Convert.ToDouble(cell.StringCellValue);
                    }
                    if (t == typeof(short))
                    {
                        value = Convert.ToInt16(cell.StringCellValue);
                    }
                    if (t == typeof(int))
                    {
                        value = Convert.ToInt32(cell.StringCellValue);
                    }
                    if (t == typeof(long))
                    {
                        value = Convert.ToInt64(cell.StringCellValue);
                    }
                    if (t == typeof(uint))
                    {
                        uint tmpValue = 0;
                        if (cell.StringCellValue == "-" || string.IsNullOrEmpty(cell.StringCellValue))
                        {
                            tmpValue = 0;
                        }
                        else if (!uint.TryParse(cell.StringCellValue.ToString(), out tmpValue))
                        {
                            byte[] idIntBytes = System.Text.Encoding.UTF8.GetBytes(cell.StringCellValue);
                            if (idIntBytes.Length == 4)
                            {
                                tmpValue = 0 | ((uint)idIntBytes[0] << 24)
                                           | ((uint)idIntBytes[1] << 16)
                                           | ((uint)idIntBytes[2] << 8)
                                           | ((uint)idIntBytes[3] << 0);
                            }
                            else if (idIntBytes.Length > 4)
                            {
                                Debug.LogErrorFormat("ID:[{0}] is too long,length shoudn't be larger than 4", cell.StringCellValue);
                            }
                        }
                        else
                        {
                            Debug.LogErrorFormat("ID:[{0}] is not the 4-char format,convert to Numeric", cell.StringCellValue);
                        }
                        value = tmpValue;
                    }
                }
                else if (cell.CellType == NPOI.SS.UserModel.CellType.Formula)
                {
                    // Get value even if cell is a formula
                    if (t == typeof(float))
                    {
                        value = Convert.ToSingle(cell.NumericCellValue);
                    }
                    if (t == typeof(double))
                    {
                        value = Convert.ToDouble(cell.NumericCellValue);
                    }
                    if (t == typeof(short))
                    {
                        value = Convert.ToInt16(cell.NumericCellValue);
                    }
                    if (t == typeof(int))
                    {
                        value = Convert.ToInt32(cell.NumericCellValue);
                    }
                    if (t == typeof(long))
                    {
                        value = Convert.ToInt64(cell.NumericCellValue);
                    }
                }
            }
            else if (t == typeof(string) || t.IsArray)
            {
                // HACK: handles the case that a cell contains numeric value
                //       but a member field in a data class is defined as string type.
                //       e.g. string s = "123"
                if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    value = cell.NumericCellValue;
                }
                else
                {
                    value = cell.StringCellValue;
                }
            }
            else if (t == typeof(bool))
            {
                value = cell.BooleanCellValue;
            }

            if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                var nc = new NullableConverter(t);
                return(nc.ConvertFrom(value));
            }

            if (t.IsEnum)
            {
                // for enum type, first get value by string then convert it to enum.
                value = cell.StringCellValue;
                return(Enum.Parse(t, value.ToString(), true));
            }
            else if (t.IsArray)
            {
                if (t.GetElementType() == typeof(float))
                {
                    return(ConvertExt.ToSingleArray((string)value));
                }

                if (t.GetElementType() == typeof(double))
                {
                    return(ConvertExt.ToDoubleArray((string)value));
                }

                if (t.GetElementType() == typeof(short))
                {
                    return(ConvertExt.ToInt16Array((string)value));
                }

                if (t.GetElementType() == typeof(int))
                {
                    return(ConvertExt.ToInt32Array((string)value));
                }

                if (t.GetElementType() == typeof(long))
                {
                    return(ConvertExt.ToInt64Array((string)value));
                }

                if (t.GetElementType() == typeof(string))
                {
                    return(ConvertExt.ToStringArray((string)value));
                }
            }

            // for all other types, convert its corresponding type.
            return(Convert.ChangeType(value, t));
        }
        public void ConvertFrom_EmptyString()
        {
            NullableConverter converter = new NullableConverter(typeof(MyType?));

            Assert.IsNull(converter.ConvertFrom(null, null, String.Empty), "#1");
        }
예제 #5
0
        protected object UnityConvertFrom(ICell cell, Type t, CellType mycell, bool myiArr)
        {
            object value = null;

            Debug.Log("mycell:" + mycell.ToString() + ",num:" + mycell + ",isArr:" + myiArr);
            if (myiArr == false)
            {
                switch (mycell)
                {
                case CellType.Undefined:
                    var nc = new NullableConverter(t);
                    Debug.Log("CT:nc");
                    return(nc.ConvertFrom(value));

                case CellType.String:
                    Debug.Log("CT:Str");
                    if (cell == null)
                    {
                        Debug.Log("CT:Str-cell is null");
                        value = "";
                    }
                    else
                    {
                        if (cell.CellType == NPOI.SS.UserModel.CellType.Blank)
                        {
                            Debug.Log("NPOI.SS.UserModel.CellType.Blank:Str-cell is null");
                            value = "";
                        }
                        else
                        {
                            if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                            {
                                if (cell.StringCellValue != null)
                                {
                                    Debug.Log("cell.StringCellV:" + cell.StringCellValue);
                                    value = cell.StringCellValue;
                                }
                                else
                                {
                                    Debug.Log("NPOI.SS.UserModel.CellType.String:Str-cell is null");
                                    value = "";
                                }
                            }
                        }
                    }
                    t = typeof(string);
                    break;

                case CellType.Short:
                    Debug.Log("CT:short");
                    if (cell == null)
                    {
                        value = (Int16)(0);
                    }
                    else
                    {
                        value = Convert.ToInt16(cell.StringCellValue);
                    }
                    t = typeof(short);
                    break;

                case CellType.Int:
                    Debug.Log("CT:Int");
                    if (cell == null)
                    {
                        value = (Int32)(0);
                    }
                    else
                    {
                        if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                        {
                            value = cell.NumericCellValue;
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                        {
                            value = Convert.ToInt32(cell.StringCellValue);
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.Blank)
                        {
                            value = (Int32)(0);
                        }
                        Debug.Log("intValue:" + value);
                    }
                    t = typeof(int);
                    break;

                case CellType.Long:
                    Debug.Log("CT:Long");
                    if (cell == null)
                    {
                        value = (Int64)(0);
                    }
                    else
                    {
                        if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                        {
                            value = cell.NumericCellValue;
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                        {
                            value = Convert.ToInt64(cell.StringCellValue);
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.Blank)
                        {
                            value = (Int64)(0);
                        }
                    }
                    t = typeof(long);
                    break;

                case CellType.Float:
                    Debug.Log("CT:Float");
                    if (cell == null)
                    {
                        value = (float)(0f);
                    }
                    else
                    {
                        if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                        {
                            value = cell.NumericCellValue;
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                        {
                            value = Convert.ToSingle(cell.StringCellValue);
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.Blank)
                        {
                            value = (float)(0f);
                        }
                    }
                    t = typeof(float);
                    break;

                case CellType.Double:
                    Debug.Log("CT:Double");
                    if (cell == null)
                    {
                        value = (double)(0.0);
                    }
                    else
                    {
                        if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                        {
                            value = cell.NumericCellValue;
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                        {
                            value = Convert.ToDouble(cell.StringCellValue);
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.Blank)
                        {
                            value = (double)(0.0);
                        }
                    }
                    Debug.Log("doubleValue:" + value);
                    t = typeof(double);
                    break;

                case CellType.Enum:
                    Debug.Log("CT:Enum");
                    if (cell == null)
                    {
                        value = (0);
                    }
                    else
                    {
                        if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                        {
                            value = cell.NumericCellValue;
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                        {
                            value = Convert.ToDouble(cell.StringCellValue);
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.Blank)
                        {
                            value = 0;
                        }
                    }
                    return(Enum.Parse(t, value.ToString(), true));

                case CellType.Bool:
                    Debug.Log("CT:Bool");
                    if (cell == null)
                    {
                        value = false;
                    }
                    else
                    {
                        value = TestBool(cell, t);
                    }
                    t = typeof(bool);
                    break;
                }
            }
            else
            {
                // string tempCell = cell.StringCellValue;
                switch (mycell)
                {
                case CellType.Bool:
                    Debug.Log("CT:Bool[]");
                    List <bool> tempListB = new List <bool>();
                    foreach (var i in ConvertExt.Split(cell.StringCellValue))
                    {
                        tempListB.Add(TestBool((string)i, t));
                    }
                    value = tempListB;
                    t     = typeof(List <bool>);
                    break;

                case CellType.Short:
                    Debug.Log("CT:Short[]");
                    List <short> tempListS = new List <short>();
                    if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                    {
                        tempListS.Add(Convert.ToInt16(cell.NumericCellValue));
                    }
                    else
                    {
                        List <short> addRS = ConvertExt.ToInt16Array(cell.StringCellValue).ToList <short>();
                        tempListS.AddRange(addRS);
                    }
                    value = tempListS;
                    t     = typeof(List <short>);
                    break;

                case CellType.Long:
                    Debug.Log("CT:Long[]");
                    List <long> tempListL = new List <long>();
                    if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                    {
                        tempListL.Add(Convert.ToInt64(cell.NumericCellValue));
                    }
                    else
                    {
                        List <long> addRL = ConvertExt.ToInt64Array(cell.StringCellValue).ToList <long>();
                        tempListL.AddRange(addRL);
                    }
                    value = tempListL;
                    t     = typeof(List <long>);
                    break;

                case CellType.Float:
                    Debug.Log("CT:Float[]");
                    List <float> tempListF = new List <float>();
                    if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                    {
                        tempListF.Add(Convert.ToSingle(cell.NumericCellValue));
                    }
                    else
                    {
                        List <float> addRF = ConvertExt.ToSingleArray(cell.StringCellValue).ToList <float>();
                        tempListF.AddRange(addRF);
                    }
                    value = tempListF;
                    t     = typeof(List <float>);
                    break;

                case CellType.Int:
                    Debug.Log("CT:Int[]");
                    List <int> tempListI = new List <int>();
                    if (cell == null)
                    {
                        Debug.Log("intArr,cell is null,add tempListI new List<int>()");
                    }
                    else
                    {
                        Debug.Log("intArr,cell.CellType:" + cell.CellType);
                        if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                        {
                            Debug.Log("C1,cell.NumericCellValue:" + cell.NumericCellValue);
                            tempListI.Add(Convert.ToInt32(cell.NumericCellValue));
                            Debug.Log("Fin!tempListI[0]:" + tempListI[tempListI.Count - 1]);
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                        {
                            Debug.Log("C2,cell.StringCellValue:" + cell.StringCellValue);
                            foreach (var i in ConvertExt.Split(cell.StringCellValue))
                            {
                                tempListI.Add(Int32.Parse((string)i));
                            }
                            Debug.Log("Fin!tempListI[0]:" + tempListI[tempListI.Count - 1]);
                        }
                        else if (cell.CellType == NPOI.SS.UserModel.CellType.Blank)
                        {
                            Debug.Log("C3,cell is blank:");
                            if (tempListI == null)
                            {
                                tempListI = new List <int>();
                            }
                            Debug.Log("Fin!tempListI is empty");
                        }
                    }

                    // value = tempListI;
                    // Type tt=typeof(List<int>);
                    // t = tt;
                    return(tempListI.ToArray());

                    // return Convert.ChangeType(value, value.GetType());
                    break;

                case CellType.String:
                    Debug.Log("CT:String[]");
                    List <string> tempListSS = new List <string>();
                    List <string> addRSS     = ConvertExt.ToStringArray(cell.StringCellValue).ToList <string>();
                    tempListSS.AddRange(addRSS);
                    value = tempListSS;
                    t     = typeof(List <string>);
                    break;
                }
            }
            Debug.Log("valueType:" + value.GetType().ToString() + ",tType:" + t.GetType().ToString());
            return(Convert.ChangeType(value, t));
        }
예제 #6
0
        /// <summary>
        /// Convert type of cell value to its predefined type which is specified in the sheet's ScriptMachine setting file.
        /// </summary>
        protected object normalConvertFrom(ICell cell, Type t)
        {
            object value = null;

            if (t == typeof(float) || t == typeof(double) || t == typeof(short) || t == typeof(int) || t == typeof(long))
            {
                if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    value = cell.NumericCellValue;
                }
                else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                {
                    //Get correct numeric value even the cell is string type but defined with a numeric type in a data class.
                    if (t == typeof(float))
                    {
                        value = Convert.ToSingle(cell.StringCellValue);
                    }
                    if (t == typeof(double))
                    {
                        value = Convert.ToDouble(cell.StringCellValue);
                    }
                    if (t == typeof(short))
                    {
                        value = Convert.ToInt16(cell.StringCellValue);
                    }
                    if (t == typeof(int))
                    {
                        value = Convert.ToInt32(cell.StringCellValue);
                    }
                    if (t == typeof(long))
                    {
                        value = Convert.ToInt64(cell.StringCellValue);
                    }
                }
                else if (cell.CellType == NPOI.SS.UserModel.CellType.Formula)
                {
                    // Get value even if cell is a formula
                    if (t == typeof(float))
                    {
                        value = Convert.ToSingle(cell.NumericCellValue);
                    }
                    if (t == typeof(double))
                    {
                        value = Convert.ToDouble(cell.NumericCellValue);
                    }
                    if (t == typeof(short))
                    {
                        value = Convert.ToInt16(cell.NumericCellValue);
                    }
                    if (t == typeof(int))
                    {
                        value = Convert.ToInt32(cell.NumericCellValue);
                    }
                    if (t == typeof(long))
                    {
                        value = Convert.ToInt64(cell.NumericCellValue);
                    }
                }
            }
            else if (t == typeof(string) || t.IsArray)
            {
                // HACK: handles the case that a cell contains numeric value
                //       but a member field in a data class is defined as string type.
                //       e.g. string s = "123"
                if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    value = cell.NumericCellValue;
                }
                else
                {
                    value = cell.StringCellValue;
                }
            }
            else if (t == typeof(bool))
            {
                value = cell.BooleanCellValue;
            }

            if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                var nc = new NullableConverter(t);
                return(nc.ConvertFrom(value));
            }

            if (t.IsEnum)
            {
                // for enum type, first get value by string then convert it to enum.
                value = cell.StringCellValue;
                return(Enum.Parse(t, value.ToString(), true));
            }
            else if (t.IsArray)
            {
                if (t.GetElementType() == typeof(float))
                {
                    return(ConvertExt.ToSingleArray((string)value));
                }

                if (t.GetElementType() == typeof(double))
                {
                    return(ConvertExt.ToDoubleArray((string)value));
                }

                if (t.GetElementType() == typeof(short))
                {
                    return(ConvertExt.ToInt16Array((string)value));
                }

                if (t.GetElementType() == typeof(int))
                {
                    return(ConvertExt.ToInt32Array((string)value));
                }

                if (t.GetElementType() == typeof(long))
                {
                    return(ConvertExt.ToInt64Array((string)value));
                }

                if (t.GetElementType() == typeof(string))
                {
                    return(ConvertExt.ToStringArray((string)value));
                }
            }

            // for all other types, convert its corresponding type.
            return(Convert.ChangeType(value, t));
        }
예제 #7
0
        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T">转换类型</typeparam>
        /// <param name="dt">数据源</param>
        /// <returns></returns>
        public static List <T> ToList <T>(this DataTable dt)
        {
            List <T> list = new List <T>();

            //确认参数有效,若无效则返回Null
            if (dt == null)
            {
                return(list);
            }
            else if (dt.Rows.Count == 0)
            {
                return(list);
            }

            Dictionary <string, string> dicField    = new Dictionary <string, string>();
            Dictionary <string, string> dicProperty = new Dictionary <string, string>();
            Type type = typeof(T);

            //创建字段字典,方便查找字段名
            type.GetFields().ForEach(aFiled =>
            {
                dicField.Add(aFiled.Name.ToLower(), aFiled.Name);
            });

            //创建属性字典,方便查找属性名
            type.GetProperties().ForEach(aProperty =>
            {
                dicProperty.Add(aProperty.Name.ToLower(), aProperty.Name);
            });

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建泛型对象
                T _t = Activator.CreateInstance <T>();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string memberKey = dt.Columns[j].ColumnName.ToLower();

                    //字段赋值
                    if (dicField.ContainsKey(memberKey))
                    {
                        FieldInfo theField = type.GetField(dicField[memberKey]);
                        var       dbValue  = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                        {
                            dbValue = null;
                        }
                        if (dbValue != null)
                        {
                            Type memberType = theField.FieldType;
                            dbValue = dbValue.ChangeType(memberType);
                        }
                        theField.SetValue(_t, dbValue);
                    }
                    //属性赋值
                    if (dicProperty.ContainsKey(memberKey))
                    {
                        PropertyInfo theProperty = type.GetProperty(dicProperty[memberKey]);
                        var          dbValue     = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                        {
                            dbValue = null;
                        }
                        if (dbValue != null)
                        {
                            Type memberType = theProperty.PropertyType;
                            if (memberType.IsGenericType && memberType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                            {
                                NullableConverter newNullableConverter = new NullableConverter(memberType);
                                dbValue = newNullableConverter.ConvertFrom(dbValue);
                            }
                            else
                            {
                                dbValue = Convert.ChangeType(dbValue, memberType);
                            }
                        }
                        theProperty.SetValue(_t, dbValue);
                    }
                }
                list.Add(_t);
            }
            return(list);
        }
 public object ConvertFrom(object value)
 {
     return(_nullableConverter.ConvertFrom(value));
 }
예제 #9
0
        private static void DeserializeType(IEnumerable <PropertyInfo> map, IDictionary <string, object> bag, object instance)
        {
            foreach (var info in map)
            {
                var key = info.Name;
                if (!bag.ContainsKey(key))
                {
                    key = NormalizePropertyName(key, '_');
                    if (!bag.ContainsKey(key))
                    {
                        key = NormalizePropertyName(key, '-');
                        if (!bag.ContainsKey(key))
                        {
                            continue;
                        }
                    }
                }

                var value = bag[key];
                if (info.PropertyType == typeof(DateTime))
                {
                    // Dates (Not part of spec, using lossy epoch convention)
                    var seconds = Int32.Parse(
                        value.ToString(), NumberStyles.Number, CultureInfo.InvariantCulture
                        );
                    var time = new DateTime(1970, 1, 1).ToUniversalTime();
                    value = time.AddSeconds(seconds);
                }

                var special = true;

                if (info.PropertyType == typeof(byte[]))
                {
                    var bytes = (List <object>)value;
                    value   = bytes.Select(Convert.ToByte).ToArray();
                    special = false;
                }

                if (info.PropertyType == typeof(int))
                {
                    value   = Convert.ToInt32(value);
                    special = false;
                }

                if (info.PropertyType == typeof(short))
                {
                    value   = Convert.ToInt16(value);
                    special = false;
                }

                if (info.PropertyType == typeof(double))
                {
                    value   = Convert.ToDouble(value);
                    special = false;
                }

                if (info.PropertyType == typeof(float))
                {
                    value   = Convert.ToSingle(value);
                    special = false;
                }

                if (info.PropertyType == typeof(int))
                {
                    value   = Convert.ToInt32(value);
                    special = false;
                }

                if (info.PropertyType == typeof(long))
                {
                    value   = Convert.ToInt64(value);
                    special = false;
                }

                if (info.PropertyType == typeof(bool))
                {
                    value   = Convert.ToBoolean(value);
                    special = false;
                }

                // TODO better handling of nullables and possibly TypeConverter for all usages
                if (info.PropertyType == typeof(bool?))
                {
                    var conv = new NullableConverter(typeof(bool?));
                    conv.ConvertFrom(value);
                    special = false;
                }

                if (info.PropertyType == typeof(double?))
                {
                    var conv = new NullableConverter(typeof(double?));
                    conv.ConvertFrom(value);
                    special = false;
                }

                if (info.PropertyType == typeof(int?))
                {
                    // totally hacked in... if you want it add it, nullable means missing
                    value = Convert.ToInt32(value);
                    //var conv = new NullableConverter(typeof(int?));
                    //conv.ConvertFrom(Convert.ToInt32(value));
                    special = false;
                }

                if (info.PropertyType == typeof(string))
                {
                    value   = value.ToString();
                    special = false;
                }

                if (special) // Includes nested types in collections and custom types
                {
                    // TODO support interfaces and multiple generic parameters
                    // http://stackoverflow.com/questions/315231/using-reflection-to-set-a-property-with-a-type-of-listcustomclass
                    if (IsSubclassOfRawGeneric(typeof(List <>), info.PropertyType))
                    {
                        var targetType = typeof(List <>).MakeGenericType(info.PropertyType.GetGenericArguments());
                        var container  = (IList)Activator.CreateInstance(targetType);

                        var source = (IEnumerable)value;
                        foreach (var item in source)
                        {
                            object i;
                            var    m = PrepareInstance(out i, info.PropertyType.GetGenericArguments()[0]);
                            DeserializeType(m, (IDictionary <string, object>)item, i);
                            container.Add(i);
                        }

                        info.SetValue(instance, container, null);
                    }
                    else
                    {
                        object i;
                        var    m = PrepareInstance(out i, info.PropertyType);
                        DeserializeType(m, (IDictionary <string, object>)value, i);
                        info.SetValue(instance, i, null);
                    }
                }
                else
                {
                    info.SetValue(instance, value, null);
                }
            }
        }
예제 #10
0
        protected object ConvertFrom(CellEntry cell, Type t)
        {
            object value = null;

            if (t == typeof(float) || t == typeof(double) || t == typeof(short) || t == typeof(int) || t == typeof(long))
            {
                string cellVal = !string.IsNullOrEmpty(cell.NumericValue) ? cell.NumericValue : cell.Value;

                if (t == typeof(float))
                {
                    value = Convert.ToSingle(cellVal);
                }
                if (t == typeof(double))
                {
                    value = Convert.ToDouble(cellVal);
                }
                if (t == typeof(short))
                {
                    value = Convert.ToInt16(cellVal);
                }
                if (t == typeof(int))
                {
                    value = Convert.ToInt32(cellVal);
                }
                if (t == typeof(long))
                {
                    value = Convert.ToInt64(cellVal);
                }
            }
            else if (t == typeof(string) || t.IsArray)
            {
                value = cell.Value;
            }
            else if (t == typeof(bool))
            {
                string cellVal = cell.Value.ToLower();
                value = cellVal == "true" || cellVal == "1";
            }

            if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                var nc = new NullableConverter(t);
                return(nc.ConvertFrom(value));
            }

            if (t.IsEnum)
            {
                // for enum type, first get value by string then convert it to enum.
                return(Enum.Parse(t, cell.Value.Trim(), true));
            }
            else if (t.IsArray)
            {
                var valueStr = (string)value;

                if (t.GetElementType() == typeof(float))
                {
                    return(valueStr.ToFloatArray());
                }

                if (t.GetElementType() == typeof(double))
                {
                    return(valueStr.ToDoubleArray());
                }

                if (t.GetElementType() == typeof(short))
                {
                    return(valueStr.ToShortArray());
                }

                if (t.GetElementType() == typeof(int))
                {
                    return(valueStr.ToIntArray());
                }

                if (t.GetElementType() == typeof(long))
                {
                    return(valueStr.ToLongArray());
                }

                if (t.GetElementType() == typeof(string))
                {
                    return(valueStr.ToStringArray());
                }
            }

            // for all other types, convert its corresponding type.
            return(Convert.ChangeType(value, t));
        }
예제 #11
0
        private static Func <object, object> GetConverter(IMapper mapper, PocoColumn pc, Type srcType, Type dstType)
        {
            Func <object, object> converter = null;

            // Get converter from the mapper
            if (pc != null)
            {
                converter = mapper.GetFromDbConverter(pc.PropertyInfo, srcType);
                if (converter != null)
                {
                    return(converter);
                }
            }

            // Standard DateTime->Utc mapper
            if (pc != null && pc.ForceToUtc && srcType == typeof(DateTime) && (dstType == typeof(DateTime) || dstType == typeof(DateTime?)))
            {
                return(delegate(object src) { return new DateTime(((DateTime)src).Ticks, DateTimeKind.Utc); });
            }

            if (srcType == typeof(TimeSpan) && (dstType == typeof(DateTime) || dstType == typeof(DateTime?)))
            {
                return(delegate(object src) { return new DateTime(((TimeSpan)src).Ticks); });
            }

            if (srcType == typeof(UInt64) && (dstType == typeof(bool) || dstType == typeof(bool?)))
            {
                //if (null != Nullable.GetUnderlyingType(dstType))
                //{
                //    var convert = new NullableConverter(dstType);
                //    return delegate (object src) { return convert.ConvertFrom(src + ""); };
                //}
                return(delegate(object src) { return src.ToBool_(); });
            }

            // Forced type conversion including integral types -> enum
            if ((dstType.IsEnum || (null != Nullable.GetUnderlyingType(dstType) && Nullable.GetUnderlyingType(dstType).IsEnum)) && IsIntegralType(srcType))
            {
                //if (srcType != typeof(int))
                //{
                //    return delegate (object src) { return Convert.ChangeType(src, typeof(int), null); };
                //}
                if (null != Nullable.GetUnderlyingType(dstType))
                {
                    var convert = new NullableConverter(dstType);
                    return(delegate(object src) { return convert.ConvertFrom(src + ""); });
                }
                else
                {
                    return(delegate(object src) { return Convert.ChangeType(src, typeof(int), null); });
                }
            }
            else if (!dstType.IsAssignableFrom(srcType))
            {
                if (dstType.IsEnum && srcType == typeof(string))
                {
                    return(delegate(object src) { return EnumMapper.EnumFromString(dstType, src + ""); });
                }
                else if (null != Nullable.GetUnderlyingType(dstType))
                {
                    var convert = new NullableConverter(dstType);
                    return(delegate(object src) { return convert.ConvertFrom(src + ""); });
                }
                else
                {
                    return(delegate(object src) { return Convert.ChangeType(src, dstType, null); });
                }
            }

            return(null);
        }