easyPOI生成的excel添加水印

项目场景:

需求要求生成的excel添加水印,这个还是第一次听到,于是研究了一下。


引入依赖

代码如下:

复制代码
implementation ('cn.afterturn:easypoi-base:4.5.0') {
        exclude  group: 'com.google.guava', module: 'guava'
        exclude  group: 'org.apache.commons', module: 'commons-compress'
    }

    implementation ('org.apache.poi:ooxml-schemas:1.4')

排除的两个因为对代码没有影响,主要是因为有代码漏洞,排除掉就OK了,但是easy POI引入的apache POI并不全,导致无法添加水印,所以必须要引入org.apache.poi:ooxml-schemas:1.4


代码:

直接上代码了。

java 复制代码
@Slf4j
public class ExcelWaterMarkUtil {
    private ExcelWaterMarkUtil() {}

    public static void excelWaterMark(Workbook workbook, String append, String username){
        ByteArrayOutputStream os = null;
        try {
            //生成水印图片并导出字节流
            BufferedImage image = createWatermarkImage(append,username);
            os = new ByteArrayOutputStream();
            ImageIO.write(image, "png", os);
            int pictureIdx = workbook.addPicture(os.toByteArray(), Workbook.PICTURE_TYPE_PNG);
            POIXMLDocumentPart poixmlDocumentPart = (POIXMLDocumentPart) workbook.getAllPictures().get(pictureIdx);
            //获取每个Sheet表并插入水印
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                XSSFSheet sheet1 = (XSSFSheet) workbook.getSheetAt(i);
                PackagePartName ppn = poixmlDocumentPart.getPackagePart().getPartName();
                String relType = XSSFRelation.IMAGES.getRelation();
                //add relation from sheet to the picture data
                PackageRelationship pr = sheet1.getPackagePart().addRelationship(ppn, TargetMode.INTERNAL, relType, null);
                //set background picture to sheet
                sheet1.getCTWorksheet().addNewPicture().setId(pr.getId());
            }

        } catch (Exception e) {
            log.error("excel文件添加水印异常",e);
        }finally {
            if (os != null){
                try {
                    os.close();
                }catch (Exception e){
                    log.error("水印图片字节流关闭异常",e);
                }
            }
        }
    }

    private static BufferedImage createWatermarkImage(String append, String username) {

        Graphics2D g = null;
        try {
            Font font = new Font("microsoft-yahei", Font.PLAIN, 20);
            int width = 300, height = 170;
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            g = image.createGraphics();

            // 背景透明 结束
            g.setColor(Color.white);
            g.fillRect(0, 0, width , height);

            g.setColor(new Color(Integer.parseInt("C5CBCF", 16)));// 设定画笔颜色
            g.setFont(font);// 设置画笔字体
            g.shear(0.1, -0.20);// 设定倾斜度

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

            String[] textArray = new String[]{ "FRP - " + append, username };

            int y = 50;
            for (int i = 0; i < textArray.length; i++) {
                g.drawString(textArray[i], 0, y);// 画出字符串
                y = y + font.getSize();
            }

            g.drawString(LocalDateTime.now(ZoneId.of(CommonConstant.CHINA_ZONE)).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), 0, y);// 画出字符串
            return image;
        }finally {
            g.dispose();// 释放画笔
        }
    }

}
相关推荐
缺点内向17 小时前
如何在C#中添加Excel文档属性?
开发语言·数据库·c#·.net·excel
shouchaobao17 小时前
仓库房进销存Excel模板合集:商品采购+出入库+库存统计一站式管理,适配仓库管理员/中小企业/个体商户
excel
chenhdowue18 小时前
如何使用 vxe-table 导出为带图片的单元格到 excel 格式文件
vue.js·excel·vxe-table·vxe-ui
码上成长18 小时前
从零实现:react&Ts--批量导入 & Excel 模版下载功能
javascript·react.js·excel
前端sweetGirl18 小时前
Excel 里 XLOOKUP 函数返回日期时找不到值显示 1/0,怎么让他不显示
excel
来鸟 鸣间1 天前
excel快速填充
excel
葡萄城技术团队2 天前
Excel 文件到底是怎么坏掉的?深入 OOXML 底层原理讲解修复策略
android·java·excel
程序边界2 天前
AI实战狂飙!Excel图表制作彻底解放双手:从数据清洗到智能预测全攻略
人工智能·excel
CodeCraft Studio2 天前
Excel处理控件Aspose.Cells教程:使用C#在Excel中创建漏斗图
ui·c#·excel·aspose·excel开发·excel漏斗图·漏斗图
wtsolutions2 天前
WPS另存为JSON,WPS导出JSON, WPS表格转换成JSON : Excel to JSON WPS插件使用指南
json·excel·wps·插件·加载项·wtsolutions