Easyexcel工具类封装及表格自动列宽设置

文章介绍了如何使用Easyexcel库在Java中进行Excel导出,包括导入依赖、封装EasyexcelUtils工具类以方便在WebController中使用,以及创建ExcelColumnHandler类动态设置表格列宽。同时,展示了如何定义实体对象以匹配Excel的列名和索引。
摘要由CSDN通过智能技术生成

Easyexcel工具类封装及表格自动列宽设置

1、导入依赖

<!-- Easyexcel依赖,版本根据个人需求自行选择 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.3.1</version>
</dependency>

2、封装工具类EasyexcelUtils

@Slf4j
public class EasyExcelUtil {
    /**
     * 导出 Excel 直接可以在Spring web Controller 中使用
     *
     * @param response  HttpServletResponse
     * @param fileName  文件名
     * @param list      数据 list,
     * @param clazz     导出结构体
     * @param sheetName 导入文件的 sheet 名
     */
    public static <T> void exportExcel(HttpServletResponse response, String fileName, List<T> list, Class<T> clazz, String sheetName) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //处理文件名
        String downloadFileName = fileName + MyDateUtils.format(new Date(), DateTimeFormat.forPattern("yyyyMMddHHmmss")) + ".xlsx";
        // 这里URLEncoder.encode可以防止中文乱码
        String fileNameEnCode = null;
        try {
            fileNameEnCode = URLEncoder.encode(downloadFileName, "UTF-8").replaceAll("\\+", "+");
        } catch (UnsupportedEncodingException e) {
            log.error("UnsupportedEncodingException: ", e);
        }
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameEnCode);
        try {
            writeExcel(response.getOutputStream(), list, clazz, sheetName);
        } catch (IOException e) {
            log.error("Excel数据导出异常:", e);
        }
    }
}

3、设置下载表格自动列宽

public class ExcelColumnHandler extends AbstractColumnWidthStyleStrategy {

    private static final int MAX_COLUMN_WIDTH = 255;
    private static final int COLUMN_WIDTH = 20;
    private  Map<Integer, Map<Integer, Integer>> CACHE = new HashMap(8);

    public ExcelColumnHandler() {
    }

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (needSetWidth) {
            Map<Integer, Integer> maxColumnWidthMap = (Map)CACHE.get(writeSheetHolder.getSheetNo());
            if (maxColumnWidthMap == null) {
                maxColumnWidthMap = new HashMap(16);
                CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
            }

            Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
            if (columnWidth >= 0) {
                if (columnWidth > MAX_COLUMN_WIDTH) {
                    columnWidth = MAX_COLUMN_WIDTH;
                }else {
                    if(columnWidth<COLUMN_WIDTH){
                        columnWidth =columnWidth*2;
                    }
                }

                Integer maxColumnWidth = (Integer)((Map)maxColumnWidthMap).get(cell.getColumnIndex());
                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    ((Map)maxColumnWidthMap).put(cell.getColumnIndex(), columnWidth);
                    writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(),  columnWidth* 256);
                }
            }
        }
    }

    private  Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
        if (isHead) {
            return cell.getStringCellValue().getBytes().length;
        } else {
            CellData cellData = (CellData)cellDataList.get(0);
            CellDataTypeEnum type = cellData.getType();
            if (type == null) {
                return -1;
            } else {
                switch(type) {
                    case STRING:
                        return cellData.getStringValue().getBytes().length;
                    case BOOLEAN:
                        return cellData.getBooleanValue().toString().getBytes().length;
                    case NUMBER:
                        return cellData.getNumberValue().toString().getBytes().length;
                    default:
                        return -1;
                }
            }
        }
    }
}

3、设置下载实体对象

@Data
public class ClassVO {

    /**
     * 主键ID
     */
    @ExcelIgnore
    private String idNo;

    /**
     * 线索编号
     */
    @ExcelProperty(value = "姓名", index = 0)
    private String name;

    /**
     * 所属区域
     */
    @ExcelProperty(value = "年龄", index = 1)
    private Integer age;

    /**
     * 来源渠道
     */
    @ExcelProperty(value = "年级", index = 2)
    private String classNo;
}

@ExcelProperty中:value对应的值为下载的列名,index为第几列

5、具体实现

public void download(HttpServletResponse response, ClassParam classParam) {
    String fileName = classParam.getFileName();
    // 查询数据库获取数据
    List<ClueVO> = getList(classParam).getData();
    EasyExcelUtil.exportExcel(response, fileName, list, ClassVO.class, fileName);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值