相关文章链接
注解
@ColumnWidth
@Data
public class WidthAndHeightData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ColumnWidth(50)
@ExcelProperty("数字标题")
private Double doubleData;
}
注解使用时表头长度无法做到动态调整,只能固定设置,每次调整表头长度时只能重新修改代码
注意:@ColumnWidth最大值只能为255,超过255*256长度时会报错
查看XSSFSheet源码
类方法
AbstractHeadColumnWidthStyleStrategy
public abstract class AbstractHeadColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head,
Integer relativeRowIndex, Boolean isHead) {
// 判断是否满足 当前行索引不为空 && (当前是表头 || 当前行索引是首行)
// 如果不满足,则说明不是表头,不需要设置
boolean needSetWidth = relativeRowIndex != null && (isHead || relativeRowIndex == 0);
if (!needSetWidth) {
return;
}
Integer width = columnWidth(head, cell.getColumnIndex());
if (width != null) {
width = width * 256;
writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), width);
}
}
protected abstract Integer columnWidth(Head head, Integer columnIndex);
}
通过继承AbstractHeadColumnWidthStyleStrategy类,实现columnWidth方法获取其对应列的宽度
SimpleColumnWidthStyleStrategy
源码查看
public class SimpleColumnWidthStyleStrategy extends AbstractHeadColumnWidthStyleStrategy {
private final Integer columnWidth;
public SimpleColumnWidthStyleStrategy(Integer columnWidth) {
this.columnWidth = columnWidth;
}
@Override
protected Integer columnWidth(Head head, Integer columnIndex) {
return columnWidth;
}
}
基本使用
通过registerWriteHandler设置策略方法调整每列的固定宽度
@Data
public class User {
@ExcelProperty(value = "用户Id")
private Integer userId;
@ExcelProperty(value = "姓名")
private String name;
@ExcelProperty(value = "手机")
private String phone;
@ExcelProperty(value = "邮箱")
private String email;
@ExcelProperty(value = "创建时间")
private Date createTime;
}
@GetMapping("/download2")
public void download2(HttpServletResponse response) {
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "a