Aspose.cell 常用封包

导出成List

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class ExcelColumnAttribute : Attribute
    {
        public ExcelColumnAttribute(int columnIndex)
        {
            ColumnIndex = columnIndex;
        }
        public ExcelColumnAttribute(string columnName)
        {
            ColumnName = columnName;
        }
        public int ColumnIndex { get; }
        public string? ColumnName { get; }
    }

        public static List<T> ExcelExportList<T>(string filePath, int sheetIndex)
        {
            List<T> dataList = new List<T>();
            Workbook workbook = new Workbook(filePath);
            Worksheet worksheet = workbook.Worksheets[sheetIndex];
            PropertyInfo[] properties = typeof(T).GetProperties();
            for (int rowIndex = 1; rowIndex <= worksheet.Cells.MaxDataRow; rowIndex++)
            {
                T myData = (T)Activator.CreateInstance(typeof(T))!;
                foreach (var property in properties)
                {
                    var attributes = property.GetCustomAttributes(typeof(ExcelColumnAttribute), false);
                    if (attributes is [ExcelColumnAttribute])
                    {
                        var at = ((ExcelColumnAttribute)attributes[0]);
                        if (string.IsNullOrEmpty(at.ColumnName)||string.IsNullOrWhiteSpace(at.ColumnName))
                        {
                            int columnIndex = at.ColumnIndex;
                            string value = worksheet.Cells[rowIndex, columnIndex].StringValue;
                            property.SetValue(myData, Convert.ChangeType(value, property.PropertyType), null);
                        }
                        else
                        {
                            string columnName = at.ColumnName;
                            string value = worksheet.Cells[$"{columnName}{rowIndex+1}"].StringValue;
                            property.SetValue(myData, Convert.ChangeType(value, property.PropertyType), null);
                        }
                       
                    }
                }
                dataList.Add(myData);
            }
            return dataList;
        }
posted @ 2023-06-04 09:54  月渊  阅读(18)  评论(0编辑  收藏  举报