import com.spire.xls.*;
import <span><a href=
"http://www.lanqibing.com/tag/java/"
title=
"View all posts in java"
target=
"_blank"
>java</a></span>.awt.*;
import <span><a href=
"http://www.lanqibing.com/tag/java/"
title=
"View all posts in java"
target=
"_blank"
>java</a></span>.awt.image.BufferedImage;
import static <span><a href=
"http://www.lanqibing.com/tag/java/"
title=
"View all posts in java"
target=
"_blank"
>java</a></span>.awt.image.BufferedImage.TYPE_INT_ARGB;
public class SingleWatermark {
public static void main(String[] args) {
Workbook wb =
new
Workbook();
wb.loadFromFile(
"test.xlsx"
);
Font font =
new
Font(
"仿宋"
, Font.PLAIN, 40);
for
(int i =0;i<wb.getWorksheets().getCount();i++)
{
Worksheet sheet = wb.getWorksheets().get(i);
BufferedImage imgWtrmrk = drawText(
"内部专用"
, font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());
sheet.getPageSetup().setCenterHeaderImage(imgWtrmrk);
sheet.getPageSetup().setCenterHeader(
"&G"
);
sheet.setViewMode(ViewMode.Layout);
}
wb.saveToFile(
"SingleWatermark.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();
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;
}
}