EasyExcel自定义表头

本文介绍了如何在Java开发中利用EasyExcel库自定义表头,以适应不同的业务需求,实现灵活的数据导出功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

表头可以根据业务进行设置,然后后续赋值对应的值。

	@Test
    public void easyExcelTest() {
        List<List<String>> heads = Lists.newArrayList();
        heads.add(Lists.newArrayList("表头1"));
        heads.add(Lists.newArrayList("表头2"));
        heads.add(Lists.newArrayList("表头3"));
        heads.add(Lists.newArrayList("表头4"));
        heads.add(Lists.newArrayList("表头5"));

        List<List<String>> contents = Lists.newArrayList();
        for (int i = 0; i <= 10; i++) {
            List<String> content = Lists.newArrayList();
            for (int j = 0; j < 5; j++) {
                content.add("第" + i + "行第" + j + "例内容");
            }
            contents.add(content);
        }

        // 表头样式策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 设置数据格式
        headWriteCellStyle.setDataFormat((short) BuiltinFormats.getBuiltinFormat("m/d/yy h:mm"));
        // 是否换行
        headWriteCellStyle.setWrapped(false);
        // 水平对齐方式
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        // 垂直对齐方式
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 前景色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        // 背景色
        headWriteCellStyle.setFillBackgroundColor(IndexedColors.WHITE.getIndex());
        // 设置为1时,单元格将被前景色填充
        headWriteCellStyle.setFillPatternType(FillPatternType.NO_FILL);
        // 控制单元格是否应自动调整大小以适应文本过长时的大小
        headWriteCellStyle.setShrinkToFit(false);
        // 单元格边框类型
        headWriteCellStyle.setBorderBottom(BorderStyle.NONE);
        headWriteCellStyle.setBorderLeft(BorderStyle.NONE);
        headWriteCellStyle.setBorderRight(BorderStyle.NONE);
        headWriteCellStyle.setBorderTop(BorderStyle.NONE);
        // 单元格边框颜色
        headWriteCellStyle.setLeftBorderColor(IndexedColors.BLACK.index);
        headWriteCellStyle.setRightBorderColor(IndexedColors.BLACK.index);
        headWriteCellStyle.setTopBorderColor(IndexedColors.BLACK.index);
        headWriteCellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        // 字体策略
        WriteFont writeFont = new WriteFont();
        // 是否加粗/黑体
        writeFont.setBold(false);
        // 字体颜色
        writeFont.setColor(Font.COLOR_NORMAL);
        // 字体名称
        writeFont.setFontName("宋体");
        // 字体大小
        writeFont.setFontHeightInPoints((short) 11);
        // 是否使用斜体
        writeFont.setItalic(false);
        // 是否在文本中使用横线删除
        writeFont.setStrikeout(false);
        // 设置要使用的文本下划线的类型
        writeFont.setUnderline(Font.U_NONE);
        // 设置要使用的字符集
        writeFont.setCharset(FontCharset.DEFAULT.getNativeId());
        headWriteCellStyle.setWriteFont(writeFont);

        // 内容样式策略策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.GENERAL);
        contentWriteCellStyle.setBorderBottom(BorderStyle.NONE);
        contentWriteCellStyle.setBorderLeft(BorderStyle.NONE);
        contentWriteCellStyle.setBorderRight(BorderStyle.NONE);
        contentWriteCellStyle.setBorderTop(BorderStyle.NONE);
        contentWriteCellStyle.setFillPatternType(FillPatternType.NO_FILL);
        contentWriteCellStyle.setWrapped(false);

        EasyExcel.write("D:\\test.xlsx").head(heads)
                .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))
                .registerWriteHandler(new SimpleColumnWidthStyleStrategy(16)) // 列宽
                .registerConverter(new LocalDateTimeConverter())
                .sheet("销售订单").doWrite(contents);

		// 通过接口调用,使用流生成文件
        /*String fileName = "导出测试";
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName, "UTF-8") + ".xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("filename", fileName);

        EasyExcel.write(response.getOutputStream()).head(heads)
                .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))
                .registerWriteHandler(new SimpleColumnWidthStyleStrategy(16)) // 列宽
                .registerConverter(new LocalDateTimeConverter())
                .sheet("销售订单").doWrite(contents);*/
    }
### 关于 EasyExcel 的部分样式设置 #### 设置表头字体样式和批注 为了在使用 EasyExcel 导出 Excel 文件时自定义表头的字体样式以及添加批注,可以利用 `HeadStyleStrategy` 和 `WriteHandler` 接口来实现特定的需求。对于字体样式的调整,可以通过创建继承自 `AbstractCellStyleStrategy` 类的对象,在其中重写相应的方法来自定义单元格风格。 ```java public class HeadFontAndCommentStrategy implements WriteHandler { @Override public void sheet(int sheetNo, Sheet sheet) {} @Override public void row(int rowNum, Row row) {} @Override public void cell(int cellNum, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { if (isHead != null && isHead){ // 自定义表头样式逻辑 CellStyle style = cell.getSheet().getWorkbook().createCellStyle(); Font font = cell.getSheet().getWorkbook().createFont(); // 设置字体大小、粗细等属性 font.setFontHeightInPoints((short) 12); font.setBold(true); // 应用字体到样式 style.setFont(font); // 如果需要还可以继续设置其他样式比如边框颜色背景等等 // ... // 将样式应用给当前cell cell.setCellStyle(style); // 添加批注功能 Drawing<?> patriarch = cell.getSheet().createDrawingPatriarch(); ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short)(cell.getColumnIndex() + 1), cell.getRowIndex(), (short)(cell.getColumnIndex() + 3), cell.getRowIndex()+2 ); Comment comment = patriarch.createCellComment(anchor); RichTextString str = new XSSFRichTextString("这里是批注内容"); comment.setString(str); cell.setCellComment(comment); } } } ``` 当完成上述策略类之后,则可以在调用 `EasyExcel.write()` 方法的时候将其作为参数传递进去: ```java EasyExcel.write(fileName, CertifyOrderDetailsExcel.class) .registerWriteHandler(new HeadFontAndCommentStrategy()) .sheet("统计") .doWrite(list); ``` 以上代码片段展示了如何通过扩展接口的方式向 EasyExcel 中加入额外的功能,从而达到更加精细控制导出文件外观的目的[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值