直接上代码
注意Workbook和sheet都是XSSF开头的这种,水印效果是整个sheet页铺满自定义文本水印
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* @author lzl
* @date 2022/10/13
* @desc:
*/
public class ExcelUtil {
/**
* add watermark to each sheet of workbook
*
* @param wb
* @throws IOException
*/
public static void addWaterMark(XSSFWorkbook wb) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = ExcelUtil.createWaterMark("小烧杯");
int pictureIdx = wb.addPicture(byteArrayOutputStream.toByteArray(), Workbook.PICTURE_TYPE_PNG);
POIXMLDocumentPart poixmlDocumentPart = wb.getAllPictures().get(pictureIdx);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
XSSFSheet xssfSheet = wb.getSheetAt(i);
PackagePartName ppn = poixmlDocumentPart.getPackagePart().getPartName();
String relType = XSSFRelation.IMAGES.getRelation();
PackageRelationship pr = xssfSheet.getPackagePart().addRelationship(ppn, TargetMode.INTERNAL, relType, null);
xssfSheet.getCTWorksheet().addNewPicture().setId(pr.getId());
// 下面三行代码可设置表格内容不可复制、编辑
// xssfSheet.protectSheet(UUID.randomUUID().toString());
// xssfSheet.lockSelectUnlockedCells();
// xssfSheet.lockSelectLockedCells();
}
}
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;
}
}