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;
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章