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


代码:

直接上代码了。

@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();// 释放画笔
        }
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在使用POI库操作Excel文件时,可以通过添加水印的方式来给Excel文件添加背景图案或文字标识。下面是一个简单的示例代码来演示如何使用POI库添加水印。 首先,我们需要导入POI库的相关类: ``` import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFSheet; ``` 然后,我们需要加载Excel文件并创建一个工作簿对象: ``` String filePath = "path/to/excel/file.xlsx"; Workbook workbook = new XSSFWorkbook(filePath); ``` 接下来,创建一个新的工作表对象,并获取当前工作表的绘图对象: ``` Sheet sheet = workbook.createSheet(); Drawing drawing = sheet.createDrawingPatriarch(); ``` 创建一个文本对象,并设置文本内容以及位置: ``` ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 2, 3, 4); TextShape text = drawing.createTextbox(anchor); text.setText("水印文字"); ``` 设置文本样式、字体、颜色等: ``` text.setLineStyle(LineStyle.NONE); text.setNoFill(true); text.setVerticalAlignment(VerticalAlignment.CENTER); text.setHorizontalAlignment(HorizontalAlignment.CENTER); text.setFontFamily("宋体"); text.setFontSize(20); text.setFillColor(IndexedColors.GREY_25_PERCENT.getIndex()); ``` 最后,保存修改并关闭Excel文件: ``` FileOutputStream fileOut = new FileOutputStream("path/to/output/file.xlsx"); workbook.write(fileOut); fileOut.close(); workbook.close(); ``` 通过以上代码,我们可以将"水印文字"添加Excel文件的水印。可以根据自己的需求调整水印的位置、样式和内容等。同时需要注意的是,以上代码适用于POI版本为4.1.2。 希望以上内容对您有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦幻D开始

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值