使用java代码给Excel加水印,代码全,进阶版

以下代码,亲测可以跑通
1、上一篇博客用了Apache POI库3.8的版本的形式对Excel加了水印,但是最近主线版本用了4.1.2的形式,由于为了保持版本的兼容性,下面有开发了Apache POI的4.1.2的版本号的方案。
pom文件为:

 <dependencies>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poiartifactId>
            <version>4.1.2version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxmlartifactId>
            <version>4.1.2version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>RELEASEversion>
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>ooxml-schemasartifactId>
            <version>1.4version>
        dependency>

    dependencies>

测试类及主要 功能代码:

package com.msl;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

import static java.awt.image.BufferedImage.TYPE_INT_ARGB;

public class ExcelWatermark0905 {
    public static void main(String[] args) {
        // 输入Excel文件路径
        //   String inputFile = "/Users/navyliu/Downloads/input/附件2-3:企业资产转让业务尽职调查报告(申请机构_业务部门填写)1.xlsx";
       //  String inputFile = "/Users/navyliu/Downloads/input/kxkj.xlsx";
        // String inputFile = "/Users/navyliu/Downloads/input/test.xlsx";
      String inputFile = "/Users/navyliu/Downloads/input/315.xlsx";

        // 输出Excel文件夹路径
        String outputFolder = "/Users/navyliu/Downloads/output";
        // 水印文字
        String watermarkText = "我是水印文字";

        try {
            FileInputStream fis = new FileInputStream(inputFile);
            XSSFWorkbook workbook = new XSSFWorkbook(fis);

            // 设置文本和字体大小
            Font font = new Font("宋体",Font.PLAIN,36);
//            XXSFont font = workbook.createFont();
//            font.setFontName("仿宋");
//            font.setFontHeightInPoints((short) 20);

            int height = 467;
            int width = 987;
            BufferedImage watermarkImage = drawText(watermarkText, font, Color.orange, Color.white, height, width);

            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            ImageIO.write(watermarkImage, "png", byteArrayOut);
            int pictureIdx = workbook.addPicture(byteArrayOut.toByteArray(), Workbook.PICTURE_TYPE_PNG);

            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                   XSSFSheet  xssfSheet =  workbook.getSheetAt(i);
                   String rID = xssfSheet.addRelation(null, XSSFRelation.IMAGE_PNG, workbook.getAllPictures().get(pictureIdx))
                        .getRelationship().getId();
                //set background picture to sheet
                xssfSheet.getCTWorksheet().addNewPicture().setId(rID);

               }

            // 保存带水印的Excel到输出文件夹
            File outputDir = new File(outputFolder);
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }
            String outputFilePath = outputFolder + "/output2.xlsx";
            FileOutputStream fos = new FileOutputStream(outputFilePath);
            workbook.write(fos);
            fos.close();

            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    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();

        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) / 4, -((int) height - liStrHeight) / 4);
        loGraphic.setFont(font);
        loGraphic.setColor(textColor);
        loGraphic.drawString(text, ((int) width - liStrWidth) / 4, ((int) height - liStrHeight) / 2);
        loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 4);
        loGraphic.drawString(text, ((int) width - liStrWidth) / 6, ((int) height - liStrHeight) / 20);
        loGraphic.dispose();
        return img;
    }
}


执行后的结果截图:
使用java代码给Excel加水印,代码全,进阶版_第1张图片
使用java代码给Excel加水印,代码全,进阶版_第2张图片

你可能感兴趣的:(java,excel,开发语言)