java excel 水印_Java 添加Excel水印

前言

Microsoft Excel没有直接的方法内置水印在Excel工作表中,我们可通过添加页眉页脚功能,将图片或文字加到Excel文档内容背后,实现类似水印的效果。但是该类水印只有在打印预览或视图模式为“页面视图”下才能直观可见。

通常情况下,水印分为文本水印和图片水印。本文将介绍如何使用Java程序来将文本以图片形式添加到Excel中,最终呈现文本水印的效果。

Jar包获取及导入方法

其一:在官网上下载

其二(推荐使用):通过

com.e-iceblue

http://repo.e-iceblue.cn/repository/maven-public/

e-iceblue

spire.xls.free

2.2.0

最终导入效果如下图所示:

a8c84f39a778

代码示例

importcom.spire.xls.*;

importjava.awt.*;

importjava.awt.image.BufferedImage;

import staticjava.awt.image.BufferedImage.TYPE_INT_ARGB;

public classAddWatermark {

public static voidmain(String[] args) {

//加载示例文档

Workbook workbook = newWorkbook();

workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//设置水印文字和字体

Font font = newFont("仿宋",Font.PLAIN, 40);

String watermark ="内部专用";

//在页眉中插入图片作为模拟水印

for (Worksheet sheet : (Iterable) workbook.getWorksheets()) {

//调用DrawText()方法创建图片

BufferedImage imgWtrmrk =drawText(watermark,font, Color.pink,

Color.white,sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());

//插入图片作为LeftHeaderImage

sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk);

sheet.getPageSetup().setLeftHeader("&G");

//设置视图模式,页眉水印仅在Layout模式下直观可见

sheet.setViewMode(ViewMode.Layout);

}

//保存文档

workbook.saveToFile("output/AddWatermark.xlsx", ExcelVersion.Version2010);

}

private staticBufferedImage drawText (String text, Font font, Color textColor, Color backColor,doubleheight, doublewidth)

{

//将用来作为水印的文本返回为图片并设置其展示样式

BufferedImage img = newBufferedImage((int) width, (int) height, TYPE_INT_ARGB);//定义图片宽度和高度

Graphics2D loGraphic = img.createGraphics();

//获取文本大小

FontMetrics loFontMetrics =loGraphic.getFontMetrics(font);

intliStrWidth= loFontMetrics.stringWidth(text);

intliStrHeight= loFontMetrics.getHeight();

//文本显示样式及位置

loGraphic.setColor(backColor);

loGraphic.fillRect(0,0,(int) width, (int) height);

loGraphic.translate(((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);

loGraphic.rotate(Math.toRadians(-45));

loGraphic.translate(-((int) width - liStrWidth) / 2, -((int) height - liStrHeight) / 2);

loGraphic.setFont(font);

loGraphic.setColor(textColor);

loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);

loGraphic.dispose();

returnimg;

}

}

添加效果

a8c84f39a778

(本文完)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值