EasyExcel中处理表头行高和内容行高

在学习easyExcek 时,发现使用easyExcek 处理表头和内容的行高十分容易只需要在类模型配置上使用@HeadRowHeight 或者@ContentRowHeight 注解实现控制。

  • 创建一个类模型配置类
// 设置表头行高度
@HeadRowHeight(40)
// 设置内容行高度
@ContentRowHeight(60)
@Data
public class User {

  private String name;

  private String age;

  private String address;
}
  • 测试主类
 public static void main(String[] args) {
     List<User> userList = new ArrayList<>();

    User user = new User();
    user.setName("李四");
    user.setAge("12");
    user.setAddress("火星");
    userList.add(user);

    EasyExcel.write("F:\\excel\\a.xls", User.class)
        .automaticMergeHead(false)
        .sheet()
        .doWrite(userList);
  }
  • 效果
    在这里插入图片描述
    总体感觉还是很easy的。

下面看看具体的源码:

  • 注解@HeadRowHeight
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface HeadRowHeight {
    /**
     * 设置表头高,默认是-1,-1 表示自动设置高度
     */
    short value() default -1;
}
  • 注解@ContentRowHeight
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ContentRowHeight {

    /**
     * 设置内容行高,默认是-1,-1 表示自动设置高度
     */
    short value() default -1;
}
  • 核心拦截器
public abstract class AbstractRowHeightStyleStrategy implements RowWriteHandler {
  // 在完成该行的所有操作后调用。在填充的情况下,可以多次调用。
  @Override
  public void afterRowDispose(RowWriteHandlerContext context) {
    if (context.getHead() == null) {
      return;
    }
    
    // 当前是否是表头,是则调用setHeadColumnHeight
    // 反之调用setContentColumnHeight
    if (context.getHead()) {
      setHeadColumnHeight(context.getRow(), context.getRelativeRowIndex());
    } else {
      setContentColumnHeight(context.getRow(), context.getRelativeRowIndex());
    }
  }

  /**
   * 设置表头行高抽象方法,需要子类进行实现
   *
   */
  protected abstract void setHeadColumnHeight(Row row, int relativeRowIndex);

  /**
   * 设置内容行高抽象方法,需要子类进行实现
   *
   */
  protected abstract void setContentColumnHeight(Row row, int relativeRowIndex);

}
  • 唯一实现类
public class SimpleRowHeightStyleStrategy extends AbstractRowHeightStyleStrategy {
  private final Short headRowHeight;
  private final Short contentRowHeight;

  public SimpleRowHeightStyleStrategy(Short headRowHeight, Short contentRowHeight) {
    this.headRowHeight = headRowHeight;
    this.contentRowHeight = contentRowHeight;
  }

  @Override
  protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
    if (headRowHeight != null) {
      row.setHeightInPoints(headRowHeight);
    }
  }

  @Override
  protected void setContentColumnHeight(Row row, int relativeRowIndex) {
    if (contentRowHeight != null) {
      row.setHeightInPoints(contentRowHeight);
    }
  }

}

在这里插入图片描述

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值