Java 给Excel 添加多行水印

 时间:2024-11-03 17:41:17

1、在IDEA项目文件下存入用于测试的Excel工作簿,这里以.xlsx格式的Excel为例,也可以是.xls格式。本次代码中的文件路径为:C:\Users\Administrator\IdeaProjects\TextWatermark_XLS。文件路径也可以自定义为其他路径。

2、在程序中引入jar文件,如下图:

Java 给Excel 添加多行水印

3、在程序中键入如下代码内容: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"); //设置文本和字体大小 Font font = new Font("仿宋", Font.PLAIN, 25); for (int i =0;i<wb.getWorksheets().getCount();i++) { Worksheet sheet = wb.getWorksheets().get(i); //调用DrawText() 方法插入图片 BufferedImage imgWtrmrk = drawText("内部专用 内部专用 内部专用 内部专用", font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth()); //将图片设置为页眉 sheet.getPageSetup().setCenterHeaderImage(imgWtrmrk); sheet.getPageSetup().setCenterHeader("&G"); //将显示模式设置为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; } }

4、完成以上代码后,执行程序,生成结果文档,可查看水印添加效果,如图所示:

Java 给Excel 添加多行水印
  • 怎样给 Excel 表格添加水印?
  • 如何使用表格制作抽奖效果
  • excel快速填充日期方法
  • 如何在excel表格中添加水印
  • 如何配置表格的单元格跳转到文件的其他工作表
  • 热门搜索
    去痘痘的最快方法 win7怎么设置密码 刮痧方法 欠钱不还怎么办最有效的方法 养肝护肝的方法和饮食 大龙虾怎么做好吃 乐姓氏怎么读 家常宫保鸡丁 肛裂的治疗方法 蒸包子发面的方法