Java 给Excel 添加多行水印

2025-10-22 17:37:35

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 添加多行水印

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢