-
第一步
- 定义导出Excel的表头一个特性,继承自Attribute,包含列头的名字和列的顺序
public class ExportHeaderAttribute : Attribute { public ExportHeaderAttribute(string name) : this(name, -1) { } public ExportHeaderAttribute(string name, short order) { Name = name; Order = order; } /// <summary> /// 列名称 /// </summary> public string Name { get; } /// <summary> /// 列顺序 /// </summary> public short Order { get; } }
-
第二步
- 在导出的Excel上面对应的model添加特性
public class ExportModel { /// <summary> /// 宽度 /// </summary> [ExportHeader("宽度", 1)] public decimal? Width { get; set; } /// <summary> /// 长度 /// </summary> [ExportHeader("长度", 2)] public decimal? Length { get; set; } /// <summary> /// 数量 /// </summary> [ExportHeader("数量",3)] public decimal? Count { get; set; } /// <summary> /// 重量 /// </summary> [ExportHeader("重量", 4)] public decimal? Weight { get; set; } }
-
第三步
- 获取导出的model,并且按照特性排序
var properties = typeof(T).GetProperties(); var columns = properties.Select(x => new ColumnEntry { Property = x, Header = x.GetCustomAttribute<ExportHeaderAttribute>() }) .Where(x => x.Header != null) .OrderBy(x => x.Header.Order) .ToList(); public class ColumnEntry { public PropertyInfo Property { get; set; } public ExportHeaderAttribute Header { get; set; } }
-
后面就是实际导出Excel的方法了,请自行参考