Java 在Excel中添加水印

4966次浏览推荐于2021.03.23

在Excel中没有直接添加水印的功能,但依旧可以通过一定方式来实现类似水印效果。下面通过Java程序代码介绍具体实现方法。

    操作方法

    • 01

      在IDEA程序项目文件夹下存储一个2013版的Excel的测试文件。如下图:

      • 02

        在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测试文档 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); //调用DrawText() 方法插入图片 BufferedImage imgWtrmrk = drawText("内部专用", font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth()); //将图片设置为页眉 sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk); sheet.getPageSetup().setLeftHeader("&G"); //将显示模式设置为Layout 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; } }

        • 03

          运行程序,生成文档,水印效果如图,但是需要注意的是:在添加完水印效果后,查看文档时,在“普通视图”水印不可见,需在“页面布局”模式或“打印预览”模式下查看。

          • End

          免责声明:

          本页搜狗指南内容仅代表作者本人意见,若因此产生任何纠纷由作者本人负责,概与搜狗公司无关。本页搜狗指南内容仅供参考,请您根据自身实际情况谨慎操作。尤其涉及您或第三方利益等事项,请咨询专业人士处理。

          0点赞无帮助无帮助
          码字人生~