在Excel中沒(méi)有直接添加水印的功能蒜绽,但依舊可以通過(guò)一定方式來(lái)實(shí)現(xiàn)類似水印效果司顿。本文通過(guò)Java程序代碼介紹具體實(shí)現(xiàn)方法秀撇。
程序環(huán)境:
- 測(cè)試文檔:Office Excel 2013
- 編譯環(huán)境:IntelliJ IDEA 2018
- JDK版本:1.8.0
- Excel庫(kù):Java系列spire.xls.jar 3.9.1(本次測(cè)試使用免費(fèi)版)
Java全部測(cè)試代碼
import com.spire.xls.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;
public class TextWatermark {
public static void main(String[] args) {
//加載Excel測(cè)試文檔
Workbook wb = new Workbook();
wb.loadFromFile("test.xlsx");
//設(shè)置文本和字體大小
Font font = new Font("仿宋", Font.PLAIN, 40);
for (int i =0;i<wb.getWorksheets().getCount();i++)
{
Worksheet sheet = wb.getWorksheets().get(i);
//調(diào)用DrawText() 方法插入圖片
BufferedImage imgWtrmrk = drawText("內(nèi)部專用", font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());
//將圖片設(shè)置為頁(yè)眉
sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk);
sheet.getPageSetup().setLeftHeader("&G");
//將顯示模式設(shè)置為L(zhǎng)ayout
sheet.setViewMode(ViewMode.Layout);
}
//保存文檔
wb.saveToFile("TextWatermark.xlsx", ExcelVersion.Version2013);
}
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();
//獲取文本size
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;
}
}
水印效果圖
以上是本文關(guān)于Java 給Excel表格添加水印的方法脐恩。也可公眾號(hào)搜索【Office文檔開發(fā)】查看更多操作Office文檔的方法。