0
0

More than 3 years have passed since last update.

Java  Excelに透かしを設定

Posted at

ワードでは最初から透かし機能が存在するのですが、エクセルでは透かし機能が存在しないので、ちょっと難しいかなと思いっていますか?実はSpire.XLS for Javaというライブラリを通して、簡単に設定できます。

下準備

1.E-iceblueの公式サイトからFree Spire. XLS for Javal無料版をダウンロードしてください。

f:id:lendoris:20210324105601p:plain

2.IDEを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire. XLS.jarを参照に追加してください。

f:id:lendoris:20210324105623p:plain

import com.spire.xls.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;

public class ExcelWatermark {
    public static void main(String[] args)  {

        //Workbook objectを作成します。
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");

        //テキストを設定します。
        Font font = new Font("Arial", Font.PLAIN, 40);
        String watermark = "Draft Version";

        for (Worksheet sheet : (Iterable) workbook.getWorksheets()) {
            //Call DrawText() method to insert the image
            BufferedImage imgWtrmrk = drawText(watermark, font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());

            //イメージをヘッダーに設定します。
            sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk);
            sheet.getPageSetup().setLeftHeader("&G");

            // ビューモードをLayoutに設定します。
            sheet.setViewMode(ViewMode.Layout);
        }

        //保存します。
        workbook.saveToFile("Watermark.xlsx", ExcelVersion.Version2010);
    }
    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) / 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;
    }
}

 実行結果

f:id:lendoris:20210324105719p:plain

 

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0