Пример #1
0
        private void SetPropertyValue(object model, PropertyInfo property, int rowIndex, List <CellValue> columnTitleCells)
        {
            // DisplayName -> columnTitle -> columnIndex
            object[]  attributes  = property.GetCustomAttributes(typeof(DisplayNameAttribute), true);
            string    displayName = ((DisplayNameAttribute)attributes[0]).DisplayName;
            CellValue cell        = columnTitleCells.FirstOrDefault(c => c.Value.ToString().Equals(displayName));

            if (cell == null)
            {
                return;
            }
            int colIndex = cell.Col;

            // 查找对应单元格的数据
            object value = CellValueCollection.FirstOrDefault(c => c.Row == rowIndex && c.Col == colIndex).Value;

            // 格式转换
            object propertyValue = null;

            if (property.PropertyType == typeof(Guid))
            {
                propertyValue = new Guid(value.ToString());
            }
            else
            {
                propertyValue = Convert.ChangeType(value, property.PropertyType);
            }
            property.SetValue(model, propertyValue, null);
        }
Пример #2
0
        /// <summary>
        /// 读取报表标题(通常在[第一行,第一列])
        /// </summary>
        /// <returns>报表标题</returns>
        public string GetExcelTitle()
        {
            if (!HasTitle)
            {
                return(string.Empty);
            }

            int titleRowIndex = MinRowIndex; // 标题行

            return(CellValueCollection.FirstOrDefault(c => c.Row == MinRowIndex && c.Col == MinColIndex).Value.ToString());
        }
Пример #3
0
        /// <summary>
        /// 将Excel中的“数据表”部分,读取到泛型集合中
        /// </summary>
        /// <typeparam name="T">集合元素的类型</typeparam>
        /// <returns>泛型集合</returns>
        public List <T> Read <T>() where T : class, new()
        {
            // 属性集合
            IEnumerable <PropertyInfo> propertyArray = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(DisplayNameAttribute), true).Length > 0);

            // 列标题集合
            List <CellValue> columnTitleCells = CellValueCollection.Where(c => c.Row == ColumnRowIndex).ToList();

            // 遍历数据行
            List <T> modelList = new List <T>();

            for (int rowIndex = DataRowIndex; rowIndex <= MaxRowIndex; rowIndex++)
            {
                object model = Activator.CreateInstance(typeof(T));
                foreach (PropertyInfo property in propertyArray)
                {
                    SetPropertyValue(model, property, rowIndex, columnTitleCells);
                }
                modelList.Add(model as T);
            }

            return(modelList);
        }