共计 2362 个字符,预计需要花费 6 分钟才能阅读完成。
前言
Microsoft Excel 没有间接的办法内置水印在 Excel 工作表中,咱们可通过增加页眉页脚性能,将图片或文字加到 Excel 文档内容背地,实现相似水印的成果。然而该类水印只有在打印预览或视图模式为“页面视图”下能力直观可见。
通常状况下,水印分为文本水印和图片水印。本文将介绍如何应用 Java 程序来将文本以图片模式增加到 Excel 中,最终出现文本水印的成果。
Jar 包获取及导入办法
其一: 在官网上下载 Free Spire.XLS for Java 产品包,解压后将 lib 文件夹下的 Spire.Xls.jar 手动导入 IDEA。
其二(举荐应用 ):通过Maven 仓库 装置导入产品及依赖。创立一个 Maven 我的项目,在 pom.xml 文件中输出以下代码,而后点击“Import Changes”即可。
<repositories> | |
<repository> | |
<id>com.e-iceblue</id> | |
<url>http://repo.e-iceblue.cn/repository/maven-public/</url> | |
</repository> | |
</repositories> | |
<dependencies> | |
<dependency> | |
<groupId>e-iceblue</groupId> | |
<artifactId>spire.xls.free</artifactId> | |
<version>2.2.0</version> | |
</dependency> | |
</dependencies> |
最终导入成果如下图所示:
代码示例
import com.spire.xls.*; | |
import java.awt.*; | |
import java.awt.image.BufferedImage; | |
import static java.awt.image.BufferedImage.TYPE_INT_ARGB; | |
public class AddWatermark {public static void main(String[] args) { | |
// 加载示例文档 | |
Workbook workbook = new Workbook(); | |
workbook.loadFromFile("C:UsersTest1DesktopSample.xlsx"); | |
// 设置水印文字和字体 | |
Font font = new Font("仿宋", Font.PLAIN, 40); | |
String watermark = "外部专用"; | |
// 在页眉中插入图片作为模仿水印 | |
for (Worksheet sheet : (Iterable<Worksheet>) 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 static BufferedImage drawText (String text, Font font, Color textColor, Color backColor,double height, double width) | |
{ | |
// 将用来作为水印的文本返回为图片并设置其展现款式 | |
BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB);// 定义图片宽度和高度 | |
Graphics2D loGraphic = img.createGraphics(); | |
// 获取文本大小 | |
FontMetrics loFontMetrics = loGraphic.getFontMetrics(font); | |
int liStrWidth = loFontMetrics.stringWidth(text); | |
int liStrHeight = 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(); | |
return img; | |
} | |
} |
增加成果
(本文完)
正文完