Skip to content

ExcelColumn 的 Index 应按序排列而非直接对应列位置 #862

@yangf85

Description

@yangf85

功能请求:ExcelColumn 的 Index 应按序排列而非直接对应列位置

问题描述

目前 ExcelColumnIndex 值直接对应 Excel 的列位置,这会导致当 Index 值不连续时出现空白列。希望能改为按 Index 值的大小顺序排序,然后连续地从第一列开始排列。

当前行为的问题

public class SheetForExcel : ModelForExcel
{
    [ExcelColumn(Name = "类别", Index = 1)]
    public string Category { get; set; } = string.Empty;
    [ExcelColumn(Name = "材料名称", Index = 3)]
    public string Name { get; set; } = string.Empty;
    [ExcelColumn(Name = "长度", Index = 5)]
    public double Length { get; set; }
    [ExcelColumn(Name = "宽度", Index = 7)]
    public double Width { get; set; }
}

当前结果:

A列(空) | B列(类别) | C列(空) | D列(材料名称) | E列(空) | F列(长度) | G列(空) | H列(宽度)

存在的问题:

  • Index=1 的属性被放在了 Excel 的第1列(B列)
  • Index=3 的属性被放在了 Excel 的第3列(D列)
  • 导致第0列(A列)、第2列(C列)、第4列(E列)、第6列(G列)都是空白
  • 浪费了 Excel 的列空间,看起来不美观
  • 容易误导用户以为有数据缺失

期望的行为

希望 Index 值仅用于排序,排序后连续地从第一列开始放置:

期望结果:

A列(类别) | B列(材料名称) | C列(长度) | D列(宽度)

逻辑说明:

  1. Index 值排序:Index=1(类别) → Index=3(材料名称) → Index=5(长度) → Index=7(宽度)
  2. 排序后连续放置:第一列、第二列、第三列、第四列
  3. Index 值只决定排序顺序,不直接对应 Excel 列位置

建议的解决方案

方案1:修改现有行为(推荐)

  • 将所有带 ExcelColumn 特性的属性按 Index 值排序
  • 排序后从第0列(A列)开始连续放置
  • 保持向后兼容,只改变列的放置逻辑

方案2:增加配置选项

// 全局配置
ExcelColumnAttribute.UseSequentialPlacement = true;

// 或者在类级别配置
[ExcelSequentialColumns]
public class SheetForExcel : ModelForExcel
{
    [ExcelColumn(Name = "类别", Index = 1)]
    public string Category { get; set; }
    // ...
}

方案3:新的特性参数

[ExcelColumn(Name = "类别", Index = 1, Sequential = true)]
public string Category { get; set; }

优势

  1. 无空白列:充分利用 Excel 列空间
  2. 更美观:数据紧凑排列,视觉效果更好
  3. 更直观:Index 值纯粹用于排序,更符合直觉
  4. 减少误解:避免用户误以为空白列代表数据缺失
  5. 灵活性:开发者可以使用任意 Index 值来控制排序,无需连续

使用场景

这个改进特别适用于:

  • 需要灵活控制列顺序但不想产生空白列的场景
  • 动态生成的 Index 值(可能不连续)
  • 需要在现有代码中插入新列而不影响其他列的 Index 值
  • 多人协作开发时,避免 Index 值冲突导致的空白列

向后兼容性考虑

  • 对于连续的 Index 值(0,1,2,3...),行为保持不变
  • 对于不连续的 Index 值,新行为消除空白列
  • 可以通过配置选项控制是否启用新行为

这个功能能否考虑实现?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions