easyexcel实现导出添加文字水印

引入jar包

由于easyexcel没有引入ooxml-schemas包,所以需要额外添加。

<!-- easyexcel依赖 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.6</version>
</dependency>
<!-- poi 添加水印 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>ooxml-schemas</artifactId>
    <version>1.4</version>
</dependency>
<!-- 使用了hutool的工具类 -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
</dependency>

新增水印配置类和WriteHandler

新增水印配置类

@Data
public class Watermark {

    /**
     * 水印内容
     */
    private String content = "";

    /**
     * 画笔颜色. eg:#C5CBCF
     */
    private String color = "#C5CBCF";

    /**
     * 字体颜色
     */
    private Font font = new Font("microsoft-yahei", Font.PLAIN, 20);

    /**
     * 水印宽、高
     */
    private int width = 300;
    private int height = 100;

    /**
     * 倾斜度
     */
    private double shear1 = 0.1;
    private double shear2 = -0.26;

    /**
     * 字体的y轴位置
     */
    private int yAxis = 50;

}

新增WriteHandler

注意:此方法只适用于XSSFWorkbook类,easyexcel默认使用的是SXSSFWorkbook类,在使用easyexcel导出时需要设置为inMemory模式,否则会抛出类型转换异常。

public class CustomWaterMarkHandler implements SheetWriteHandler {

    private final Watermark watermark;

    public CustomWaterMarkHandler(Watermark watermark) {
        this.watermark = watermark;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        try {
            BufferedImage bufferedImage = createWatermarkImage();
            setWaterMarkToExcel((XSSFWorkbook) writeWorkbookHolder.getWorkbook(), bufferedImage);
        } catch (Exception e) {
            throw new RuntimeException("添加水印出错");
        }
    }

    private BufferedImage createWatermarkImage() {
        final Font font = watermark.getFont();
        final int width = watermark.getWidth();
        final int height = watermark.getHeight();

        String[] textArray = watermark.getContent().split(",");
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 背景透明 开始
        Graphics2D g = image.createGraphics();
        image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g.dispose();
        // 背景透明 结束
        g = image.createGraphics();
        // 设定画笔颜色
        g.setColor(new Color(Integer.parseInt(watermark.getColor().substring(1), 16)));
        // 设置画笔字体
        g.setFont(font);
        // 设定倾斜度
        g.shear(watermark.getShear1(), watermark.getShear2());

        // 设置字体平滑
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        int y = watermark.getYAxis();
        for (String s : textArray) {
            // 从画框的y轴开始画字符串.假设电脑屏幕中心为0,y轴为正数则在下方
            g.drawString(s, 0, y);
            y = y + font.getSize();
        }

        // 释放画笔
        g.dispose();
        return image;
    }

    private void setWaterMarkToExcel(XSSFWorkbook workbook, BufferedImage bfi) {
        //将图片添加到工作簿
        int pictureIdx = workbook.addPicture(ImgUtil.toBytes(bfi, ImgUtil.IMAGE_TYPE_PNG), Workbook.PICTURE_TYPE_PNG);
        //建立 sheet 和 图片 的关联关系
        XSSFPictureData xssfPictureData = workbook.getAllPictures().get(pictureIdx);
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            XSSFSheet xssfSheet = workbook.getSheetAt(i);
            PackagePartName packagePartName = xssfPictureData.getPackagePart().getPartName();
            PackageRelationship packageRelationship = xssfSheet.getPackagePart()
                    .addRelationship(packagePartName, TargetMode.INTERNAL, XSSFRelation.IMAGES.getRelation(), null);
            //添加水印到工作表
            xssfSheet.getCTWorksheet().addNewPicture().setId(packageRelationship.getId());
        }
    }
}

测试

//水印配置
Watermark watermark = new Watermark();
watermark.setContent("测试文字水印");
watermark.setWidth(500);
watermark.setHeight(200);
watermark.setYAxis(200);

//导出
EasyExcel.write(outputStream, Test.class)
        .inMemory(true)
        .sheet("sheet1")
        .registerWriteHandler(new CustomWaterMarkHandler(watermark))
        .doWrite(Collections.singletonList(new Test()));

热门相关:骑士归来   大神你人设崩了   网游之逆天飞扬   大神你人设崩了   仗剑高歌