Java基于POI来给导出的Excel动态添加水印
起因
客户提了一个要在导出的Excel里添加导出人员账号和姓名水印的功能,水印常见于ppt和pdf中,Excel用到水印的情况大部分用于打印,而客户这里的Excel加上水印后还要求可以编辑Excel,所以网上大部分插入图片的水印方法就不能用了,这里用到的是将水印设为背景图片的方法。
这是生成水印图片的方法
public static ByteArrayOutputStream createWaterMark(String content)
throws IOException {
int width = 200;
int height = 150;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);// 获取bufferedImage对象
String fontType = "微软雅黑";
int fontStyle = Font.BOLD;
int fontSize = 20;
Font font = new Font(fontType, fontStyle, fontSize);
Graphics2D g2d = image.createGraphics(); // 获取Graphics2d对象
image = g2d.getDeviceConfiguration().createCompatibleImage(width,
height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
g2d.setColor(new Color(0, 0, 0, 20)); // 设置字体颜色和透明度,最后一个参数为透明度
g2d.setStroke(new BasicStroke(1)); // 设置字体
g2d.setFont(font); // 设置字体类型 加粗 大小
g2d.rotate(-0.5, (double) image.getWidth() / 2,
(double) image.getHeight() / 2);// 设置倾斜度
FontRenderContext context = g2d.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(content, context);
double x = (width - bounds.getWidth()) / 2;
double y = (height - bounds.getHeight()) / 2;
double ascent = -bounds.getY();
double baseY = y + ascent;
// 写入水印文字原定高度过小,所以累计写水印,增加高度
g2d.drawString(content, (int) x, (int) baseY);
// 设置透明度
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// 释放对象
g2d.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "png", os);
return os;
将图片设为Excel背景(导出用的公司封装的方法,这里就不写了)
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
//userxx是导出人员账号和姓名的动态变量,根据自己的需求设置
ByteArrayOutputStream byteArrayOutputStream = WaterMarkHandler.createWaterMark(userxx);
int pictureIdx = workbook.addPicture(byteArrayOutputStream.toByteArray()
,Workbook.PICTURE_TYPE_PNG);
String rID = sheet.addRelation(null, XSSFRelation.IMAGES,workbook
.getAllPictures().get(pictureIdx)).getRelationship().getId();
sheet.getCTWorksheet().addNewPicture().setId(rID);
效果图
主要参考学习于这篇文章https://www.jianshu.com/p/4332f5feab2e,如果不理解的可以去看看原文章。
小白的工作心得,写的第一篇文章,有不对的地方望指出,希望对大家有所帮助。