在IDEA項目文件夾下存入用于測試的Excel文件,如本次文件路徑:C:\Users\Administrator\IdeaProjects\TextWatermark_XLS(文件路徑可以自定義為其他路徑)
在程序中導(dǎo)入spire.xls.jar文件,如下圖:
文章插圖
鍵入如下代碼:
import com.spire.xls.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;
public class TiledWatermark {
public static void main(String[] args) {
//加載Excel測試文檔
Workbook wb = new Workbook();
wb.loadFromFile("test.xlsx");
//設(shè)置文本和字體大小
Font font = new Font("仿宋", Font.PLAIN, 25);
for (int i =0;i<wb.getWorksheets().getCount();i++)
{
Worksheet sheet = wb.getWorksheets().get(i);
//調(diào)用DrawText() 方法插入圖片
BufferedImage imgWtrmrk = drawText("內(nèi)部專用內(nèi)部專用內(nèi)部專用內(nèi)部專用", font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());
//將圖片設(shè)置為頁眉
sheet.getPageSetup().setCenterHeaderImage(imgWtrmrk);
sheet.getPageSetup().setCenterHeader("&G");
//將顯示模式設(shè)置為Layout
sheet.setViewMode(ViewMode.Layout);
}
//保存文檔
wb.saveToFile("TiledWatermark.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) /6 , ((int) height - liStrHeight) /6);
loGraphic.drawString(text,((int) width - liStrWidth) /3, ((int) height - liStrHeight) /3);
loGraphic.drawString(text,((int) width - liStrWidth) /2, ((int) height - liStrHeight) /2);
loGraphic.dispose();
return img;
}
}
運行程序,生成如下Excel文檔 。多行水印效果如圖:
文章插圖
以上關(guān)于本文的內(nèi)容,僅作參考!溫馨提示:如遇健康、疾病相關(guān)的問題,請您及時就醫(yī)或請專業(yè)人士給予相關(guān)指導(dǎo)!
「愛刨根生活網(wǎng)」www.malaban59.cn小編還為您精選了以下內(nèi)容,希望對您有所幫助:- 附VB.NET代碼)(c# 將xml轉(zhuǎn)csv C# 將XML轉(zhuǎn)為Excel
- 怎么把桌面共享給別人遠(yuǎn)程操作 怎么把桌面共享給別人
- 表格如何導(dǎo)入cad中 CAD中如何插入表格并輸出到Excel中?優(yōu)質(zhì)
- cad表格怎么導(dǎo)出excel表格需要什么插件 CAD表格怎么導(dǎo)出Excel表格
- 如何將cad的圖導(dǎo)出來 如何從cad圖導(dǎo)出到excel
- cad里的表格中的圖紙怎么導(dǎo)出excel CAD圖紙中的表格如何導(dǎo)出到excel表格
- excel表格中數(shù)據(jù)相減用什么公式 如何在Excel中用公式計算單元格之間的相減
- excel 2010怎么設(shè)置自動調(diào)整列寬 Excel2013中如何自動調(diào)整列寬
- excel如何自動調(diào)整列寬和行高 excel如何自動調(diào)整列寬
- 久坐帶來的危害讓你害怕 六步簡易操給你全身放松
