观看记录
  • 我的观影记录
登录
Java 给Excel添加多行文本水印

Java 给Excel添加多行文本水印

在Excel中添加水印可添加单一水印效果,即水印是以单个文本字样来呈现;也可添加多个平铺水印效果,即水印是以多个文本字样来页面中平铺。详细内容见下文。

操作方式

  • 01

    在IDEA项目文件夹下存入用于测试的Excel文件,如本次文件路径:C:\Users\Administrator\IdeaProjects\TextWatermark_XLS(文件路径可以自界说为其他路径)

  • 02

    在程序中导入spire.xls.jar文件,如下图:

  • 03

    键入如下代码:
    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;
    }
    }

  • 04

    运行程序,生当作如下Excel文档。多行水印结果如图:

  • End
切换深色外观
留言
回到顶部
首页
手机数码
医疗健康
金融管理
社交情感
无名