前言
Microsoft Excel沒(méi)有直接的方法內(nèi)置水印在Excel工作表中仿耽,我們可通過(guò)添加頁(yè)眉頁(yè)腳功能叉袍,將圖片或文字加到Excel文檔內(nèi)容背后脸爱,實(shí)現(xiàn)類(lèi)似水印的效果剖笙。但是該類(lèi)水印只有在打印預(yù)覽或視圖模式為“頁(yè)面視圖”下才能直觀可見(jiàn)。
通常情況下涧窒,水印分為文本水印和圖片水印心肪。本文將介紹如何使用Java程序來(lái)將文本以圖片形式添加到Excel中,最終呈現(xiàn)文本水印的效果纠吴。
Jar包獲取及導(dǎo)入方法
其一: 在官網(wǎng)上下載Free Spire.XLS for Java產(chǎn)品包硬鞍,解壓后將lib文件夾下的Spire.Xls.jar手動(dòng)導(dǎo)入IDEA。
其二(推薦使用):通過(guò)Maven倉(cāng)庫(kù)安裝導(dǎo)入產(chǎn)品及依賴(lài)戴已。創(chuàng)建一個(gè)Maven項(xiàng)目固该,在pom.xml文件中輸入以下代碼,然后點(diǎn)擊“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>
最終導(dǎo)入效果如下圖所示:
代碼示例
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:\\Users\\Test1\\Desktop\\Sample.xlsx");
//設(shè)置水印文字和字體
Font font = new Font("仿宋",Font.PLAIN, 40);
String watermark ="內(nèi)部專(zhuān)用";
//在頁(yè)眉中插入圖片作為模擬水印
for (Worksheet sheet : (Iterable<Worksheet>) workbook.getWorksheets()) {
//調(diào)用DrawText()方法創(chuàng)建圖片
BufferedImage imgWtrmrk =drawText(watermark,font, Color.pink,
Color.white,sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());
//插入圖片作為L(zhǎng)eftHeaderImage
sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk);
sheet.getPageSetup().setLeftHeader("&G");
//設(shè)置視圖模式伐坏,頁(yè)眉水印僅在Layout模式下直觀可見(jiàn)
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)
??? {
//將用來(lái)作為水印的文本返回為圖片并設(shè)置其展示樣式
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;
??? }
}
添加效果
(本文完)