ワードでは最初から透かし機能が存在するのですが、エクセルでは透かし機能が存在しないので、ちょっと難しいかなと思いっていますか?実はSpire.XLS for Javaというライブラリを通して、簡単に設定できます。
下準備
1.E-iceblueの公式サイトからFree Spire. XLS for Javal無料版をダウンロードしてください。
2.IDEを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire. XLS.jarを参照に追加してください。
```JAVA 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;
}
}
<h4> <strong>実行結果</strong></h4>
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20210324/20210324105719.png" alt="f:id:lendoris:20210324105719p:plain" title="" class="hatena-fotolife" itemprop="image" /></p>
<p> </p>