SoFunction
Updated on 2025-03-07

Steps to create an execl import tool class


public class XlsFileHandler<T> where T : new()
    {
        private readonly string _path;
        private readonly Dictionary<string, CellAttribute> _cellAttributes;
        readonly Dictionary<string, string> _propDictionary;

        public XlsFileHandler(string path)
        {
            _path = path;
            _cellAttributes = new Dictionary<string, CellAttribute>();
            _propDictionary = new Dictionary<string, string>();
            CreateMappers();
        }

        /// <summary>
/// Create a map
        /// </summary>
        private void CreateMappers()
        {
            foreach (var prop in typeof(T).GetProperties())
            {
                foreach (CellAttribute cellMapper in (false).OfType<CellAttribute>())
                {
                    _propDictionary.Add(, );
                    _cellAttributes.Add(, cellMapper);
                }
            }
        }

        /// <summary>
/// Get the T object corresponding to the entire xls file
        /// </summary>
        /// <returns></returns>
        public List<T> ToData()
        {
            List<T> dataList = new List<T>();
            using (FileStream stream = GetStream())
            {
                IWorkbook workbook = new HSSFWorkbook(stream);
                ISheet sheet = (0);
                var rows = ();
                int lastCell = 0;
                int i = 0;
                IRow headRow = null;
                while (())
                {
                    var row = (i);
                    if (i == 0)
                    {
                        headRow = (0);
                        lastCell = ;
                    }
                    else
                    {
                        T t = GetData(workbook, headRow, row, lastCell);
                        (t);
                    }
                    i++;
                }
                ();
            }
            return dataList;
        }

        /// <summary>
/// Get T object
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="headRow"></param>
        /// <param name="currentRow"></param>
        /// <param name="lastCell"></param>
        /// <returns></returns>
        private T GetData(IWorkbook workbook, IRow headRow, IRow currentRow, int lastCell)
        {
            T t = new T();
            for (int j = 0; j < lastCell; j++)
            {
                var displayName = [j].StringCellValue;
                if (!_cellAttributes.ContainsKey(displayName) || !_propDictionary.ContainsKey(displayName))
                {
                    continue;
                }
                var currentAttr = _cellAttributes[displayName];
                var propName = _propDictionary[displayName];

                ICell currentCell = (j);
                string value = currentCell != null ? GetCellValue(workbook, currentCell) : "";
                if ( != null)
                {
                    SetValue(ref t, propName, InvokeHandler(, value));
                }
                else
                {
                    SetValue(ref t, propName, value);
                }
            }
            return t;
        }

        /// <summary>
/// Dynamic execution processing method
        /// </summary>
        /// <param name="type"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static object InvokeHandler(Type type, object value)
        {
            constructor = ();
            if (constructor == null) throw new ArgumentNullException("type");
            object mgConstructor = (null);
            method = ("GetResults");
            return (mgConstructor, new[] { value });
        }

        /// <summary>
/// Get file stream
        /// </summary>
        /// <returns></returns>
        private FileStream GetStream()
        {
            if (!(_path)) throw new FileNotFoundException("path");
            return new FileStream(_path, , , );
        }

        /// <summary>
/// Get the value of the xls file cell
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static string GetCellValue(IWorkbook workbook, ICell cell)
        {
            string value;
            switch ()
            {
                case :
                    HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);
                    value = (cell).FormatAsString();
                    break;
                default:
                    value = ();
                    break;
            }
            return value;
        }

        /// <summary>
/// Set the T attribute value
        /// </summary>
        /// <param name="t"></param>
        /// <param name="propName"></param>
        /// <param name="value"></param>
        private static void SetValue(ref T t, string propName, object value)
        {
            var typeName = ().GetProperty(propName).;
            var property = ().GetProperty(propName);
            switch (typeName)
            {
                case "Int32":
                    (t, Convert.ToInt32(value), null);
                    break;
                case "DateTime":
                    (t, (value), null);
                    break;
                case "Decimal":
                    (t, (value), null);
                    break;
                default:
                    (t, value, null);
                    break;
            }
        }
    }