Excel添加水印


Excel添加水印【源碼下載

步驟一:根據生成圖片的類創建水印圖片

步驟二:

  •   代碼在Excel中根據第一行獲取sheet的列數【sheet.getRow(0).getLastCellNum() 】,根據【sheet.getLastRowNum()】獲取整個sheet的行數。
  •   使用【sheet.protectSheet(UUID.randomUUID().toString());】為每個sheet添加密碼,防止sheet被修改
  •   在Excel中添加水印
                    /*
                     * 參數定義: 第一個參數是(x軸的開始節點); 第二個參數是(是y軸的開始節點); 第三個參數是(是x軸的結束節點);
                     * 第四個參數是(是y軸的結束節點); 第五個參數是(是從Excel的第幾列開始插入圖片,從0開始計數);
                     * 第六個參數是(是從excel的第幾行開始插入圖片,從0開始計數); 第七個參數是(圖片寬度,共多少列);
                     * 第8個參數是(圖片高度,共多少行);
                     */
                    ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, xIndexInteger,
                            yIndexInteger, xIndexInteger+waterRemarkWidth, yIndexInteger+waterRemarkHeight);
                    
                    Picture pic = drawing.createPicture(anchor,
                            wb.addPicture(byteArrayOut.toByteArray(), Workbook.PICTURE_TYPE_PNG));
                    pic.resize();

案例源碼:

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelWaterRemarkUtils {
    public static void main(String[] args) throws Exception {
        String waterRemarkPath = "E:\\NO5\\123.png";
        String tmpName = "E:\\NO5\\測試.xlsx";
        String tmpName2 = "E:\\NO5\\測試2.xlsx";
        Date a = new Date();
        XSSFWorkbook wb=new XSSFWorkbook(new FileInputStream(tmpName));
        //添加水印
        ExcelWaterRemarkUtils.betweenYRow(wb, waterRemarkPath);
        
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        byte[] content = os.toByteArray();
        File file1 = new File(tmpName2);// Excel文件生成后存儲的位置。
        OutputStream fos = new FileOutputStream(file1);
        fos.write(content);
        os.close();
        fos.close();

        Date b = new Date();
        long interval = (b.getTime() - a.getTime())/1000;
        System.out.println("兩個時間相差"+interval+"秒");//會打印出相差幾秒
        System.out.println("jdldbjo");
    }
    
    /**
     * 為Excel打上水印工具函數 請自行確保參數值,以保證水印圖片之間不會覆蓋。 在計算水印的位置的時候,並沒有考慮到單元格合並的情況,請注意
     * 
     * @param wb
     *            Excel Workbook
     * @param sheet
     *            需要打水印的Excel
     * @param waterRemarkPath
     *            水印地址,classPath,目前只支持png格式的圖片,
     *            因為非png格式的圖片打到Excel上后可能會有圖片變紅的問題,且不容易做出透明效果。
     *            同時請注意傳入的地址格式,應該為類似:"\\excelTemplate\\test.png"
     * @param startXCol
     *            水印起始列
     * @param startYRow
     *            水印起始行
     * @param betweenXCol
     *            水印橫向之間間隔多少列
     * @param betweenYRow
     *            水印縱向之間間隔多少行
     * @param XCount
     *            橫向共有水印多少個
     * @param YCount
     *            縱向共有水印多少個
     * @param waterRemarkWidth
     *            水印圖片寬度為多少列
     * @param waterRemarkHeight
     *            水印圖片高度為多少行
     * @throws IOException
     */
    public static void betweenYRow(Workbook wb, String waterRemarkPath) throws Exception {
        int startXCol=0;         //水印起始列
        int startYRow=0;         // 水印起始行
        int betweenXCol=1;       //水印橫向之間間隔多少列
        int betweenYRow=3;       //水印縱向之間間隔多少行
        int XCount=0;            //橫向共有水印多少個
        int YCount=0;            //縱向共有水印多少個
        int waterRemarkWidth=0;  //水印圖片寬度為多少列
        int waterRemarkHeight=0; // 水印圖片高度為多少行
        
        // 校驗傳入的水印圖片格式
        if (!waterRemarkPath.endsWith("png") && !waterRemarkPath.endsWith("PNG")) {
            throw new RuntimeException("向Excel上面打印水印,目前支持png格式的圖片。");
        }

        // 加載圖片
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        InputStream imageIn=new FileInputStream(waterRemarkPath);
        if (null == imageIn || imageIn.available() < 1) {
            throw new RuntimeException("向Excel上面打印水印,讀取水印圖片失敗(1)。");
        }
        BufferedImage bufferImg = ImageIO.read(imageIn);
        if (null == bufferImg) {
            throw new RuntimeException("向Excel上面打印水印,讀取水印圖片失敗(2)。");
        }
        ImageIO.write(bufferImg, "png", byteArrayOut);
        
        for(int i=0; i<wb.getNumberOfSheets(); i++){  // wb.getNumberOfSheets()
            System.err.println("num:"+ wb.getNumberOfSheets());
            System.err.println("i:"+ i);
            Sheet sheet = wb.getSheetAt(i);
            sheet.protectSheet(UUID.randomUUID().toString());
            try {
                XCount = (sheet.getRow(0).getLastCellNum()); //橫向共有水印多少個
                if(XCount == 0){
                    XCount = 2;
                }
                if(XCount >= 5){
                    XCount = 5;
                }
                
            } catch (Exception e) {
                XCount = 10;
            }
            try {
                YCount=sheet.getLastRowNum()/(betweenYRow); //縱向共有水印多少個
                if(YCount < 6){
                    YCount = 6;
                }
                
            } catch (Exception e) {
                YCount = 50;
            }
            
            System.err.println("XCount:"+ XCount);
            System.err.println("YCount:"+ YCount);
            // 開始打水印
            Drawing drawing = sheet.createDrawingPatriarch();
            // 按照共需打印多少行水印進行循環
            for (int yCount = 0; yCount < YCount; yCount++) {
                // 按照每行需要打印多少個水印進行循環
                for (int xCount = 0; xCount < XCount; xCount++) {
                    // 創建水印圖片位置
                    int xIndexInteger = startXCol + (xCount * waterRemarkWidth) + (xCount * betweenXCol);
                    int yIndexInteger = startYRow + (yCount * waterRemarkHeight) + (yCount * betweenYRow);
                    /*
                     * 參數定義: 第一個參數是(x軸的開始節點); 第二個參數是(是y軸的開始節點); 第三個參數是(是x軸的結束節點);
                     * 第四個參數是(是y軸的結束節點); 第五個參數是(是從Excel的第幾列開始插入圖片,從0開始計數);
                     * 第六個參數是(是從excel的第幾行開始插入圖片,從0開始計數); 第七個參數是(圖片寬度,共多少列);
                     * 第8個參數是(圖片高度,共多少行);
                     */
                    //System.err.println("xIndexInteger:"+ xIndexInteger+", yIndexInteger:"+ yIndexInteger);
                    ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, xIndexInteger,
                            yIndexInteger, xIndexInteger+waterRemarkWidth, yIndexInteger+waterRemarkHeight);
                    
                    Picture pic = drawing.createPicture(anchor,
                            wb.addPicture(byteArrayOut.toByteArray(), Workbook.PICTURE_TYPE_PNG));
                    pic.resize();
                    
                }
            }
        }
    }
}

生成水印圖片的源碼:

/**
     * 
     * @param content  水印文字
     * @param path     圖片生成路徑
     * @throws IOException 
     * 
     */
    public static void createWaterMark(String content,String path) throws IOException{
        Integer width = 120;
        Integer height = 90;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 獲取bufferedImage對象
        String fontType = "宋體";
        Integer fontStyle = 0;
        Integer fontSize = 16;
        Font font = new Font(fontType, fontStyle, fontSize);
        Graphics2D g2d = image.createGraphics(); // 獲取Graphics2d對象
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d.dispose();
        g2d = image.createGraphics();
        g2d.setColor(new Color(0, 0, 0, 50)); //設置字體顏色和透明度
        g2d.setStroke(new BasicStroke(1)); // 設置字體
        g2d.setFont(font); // 設置字體類型  加粗 大小
        
        g2d.rotate(Math.toRadians(-10),(double) image.getWidth() / 2, (double) image.getHeight() / 2);//設置傾斜度
        
        FontRenderContext context = g2d.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(content, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = -bounds.getY();
        double baseY = y + ascent;
        // 寫入水印文字原定高度過小,所以累計寫水印,增加高度
        g2d.drawString(content, (int)x, (int)baseY);
        // 設置透明度
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 釋放對象
        g2d.dispose();
        ImageIO.write(image, "png", new File(path));
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM