之前的代码是通过poi包导出xls文件,在poi相关类里面操作水印,尝试了好几次都没有成功。后来换成poi-ooxml包导出xlsx添加水印成功。下面是导出xlsx添加水印的相关代码。
1、添加相关依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.22</version>
</dependency>
<!-- Apache POI for Excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<!-- Apache POI dependencies -->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>5.1.1</version>
</dependency>
2、生成水印代码
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;
}
目前生成图片的效果图如下,如果像调整谁
3、excel调用水印代码
public static void main(String[] args) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
ByteArrayOutputStream byteArrayOutputStream = createWaterMark("水印内容");
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);
// 创建一个行对象
XSSFRow row = sheet.createRow(0); // 第一行
// 在行中创建单元格并设置值
XSSFCell cell = row.createCell(0); // 第一列
cell.setCellValue("Hello, Excel!");
// 写入到文件系统
try (FileOutputStream outputStream = new FileOutputStream("Example.xlsx")) {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}