在IDEA程序項(xiàng)目文件夾下存儲(chǔ)一個(gè)2013版的Excel的測(cè)試文件 。如下圖:
文章插圖
在idea中鍵入如下代碼:
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;
}
}
運(yùn)行程序,生成文檔,水印效果如圖,但是需要注意的是:在添加完水印效果后,查看文檔時(shí),在“普通視圖”水印不可見(jiàn),需在“頁(yè)面布局”模式或“打印預(yù)覽”模式下查看 。
文章插圖
以上關(guān)于本文的內(nèi)容,僅作參考!溫馨提示:如遇健康、疾病相關(guān)的問(wèn)題,請(qǐng)您及時(shí)就醫(yī)或請(qǐng)專業(yè)人士給予相關(guān)指導(dǎo)!
「愛(ài)刨根生活網(wǎng)」www.malaban59.cn小編還為您精選了以下內(nèi)容,希望對(duì)您有所幫助:- excel如何添加簽名 Java 給Excel添加數(shù)字簽名
- Java 高亮PPT中的指定文本
- java讀取excel中的圖片 Java 獲取Excel批注中的圖片
- Java如何設(shè)置PPT中的形狀排列方式
- ppt怎樣添加水印文字 Java在PPT幻燈片中添加文字水印效果
- 司儀是什么意思
- lolhentai:紅翡翠價(jià)格 紅翡翠價(jià)格現(xiàn)在是多少及圖片
- 四十周年結(jié)婚是什么婚
- 36年結(jié)婚是什么婚
- 結(jié)婚七年是什么婚
