该文将介绍如何使用spire.xls for java在excel工作表中添加文本水印和图片水印。excel 水印在正常模式下不可见,仅在页面布局模式或打印预览模式可见。
import com.spire.xls.*;
import java.awt.*;
import java.awt.image.bufferedimage;
import static java.awt.image.bufferedimage.type_int_argb;
public class excelwatermark {
public static void main(string[] args) {
//加载示例文档
workbook workbook = new workbook();
workbook.loadfromfile("sample.xlsx");
//设置文本和字体大小
font font = new font("仿宋", font.plain, 40);
string watermark = "内部专用";
for (worksheet sheet : (iterable) workbook.getworksheets()) {
//调用drawtext() 方法插入图片
bufferedimage imgwtrmrk = drawtext(watermark, font, color.pink, color.white, sheet.getpagesetup().getpageheight(), sheet.getpagesetup().getpagewidth());
//将图片设置为页眉
sheet.getpagesetup().setleftheaderimage(imgwtrmrk);
sheet.getpagesetup().setleftheader("&g");
//将显示模式设置为layout
sheet.setviewmode(viewmode.layout);
}
//保存文档
workbook.savetofile("watermark.xlsx", excelversion.version2010);
}
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;
}
}
excel工作表添加文本水印效果图: