本文共 3035 字,大约阅读时间需要 10 分钟。
在项目中引入必要的库文件,可以通过以下方式实现:
org.apache.poi poi 4.1.2 net.sourceforge.jexcelapi jxl 2.6.11
package org.publiccms.common.excelutil;import java.awt.AlphaComposite;import java.awt.BasicStroke;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.ImageIO;import java.io.File;import java.io.IOException;public class Utilss { private static int width = 800; private static int height = 1020; public static File createWaterMark(String watermark) throws IOException { File file = new File("watermark.bmp"); BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.setColor(Color.LIGHT_GRAY); g2.setFont(new Font("Serif", Font.ITALIC, 20)); g2.rotate(Math.toRadians(0), width / 2, height / 2); Rectangle2D bounds = g2.getFontRenderContext().getStringBounds(watermark, g2); g2.drawString(watermark, (int) (width - bounds.getWidth()) / 2, (int) (height - bounds.getHeight()) / 2); ImageIO.write(bi, "bmp", file); return file; } public static File createWaterMark1(String watermarkMessage) throws IOException { File file = new File("watermark.bmp"); BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { bi.setRGB(i, j, 0xFFFFFF); } } Graphics2D g2d = bi.createGraphics(); g2d.setColor(Color.LIGHT_GRAY); g2d.setFont(new Font("Serif", Font.ITALIC, 40)); g2d.rotate(Math.toRadians(-8)); for (int i = 1; i < 7; i++) { g2d.drawString(" : " + watermarkMessage, 0, 180 * i + 40 * (i + 1)); } g2d.dispose(); ImageIO.write(bi, "bmp", file); return file; }} package org.publiccms.common.excelutil;import myjxl.Workbook;import myjxl.write.WritableSheet;import myjxl.write.WritableWorkbook;public class ExcelUtil { public static void addWatermark(String watermarkText) throws Exception { File inputStreamFile = new File("in.xls"); File outputFilePath = new File("out.xls"); Workbook wb = Workbook.getWorkbook(new FileInputStream(inputStreamFile)); WritableWorkbook wwb = Workbook.createWorkbook(outputFilePath, wb); WritableSheet ws = wwb.getSheet(0); File watermarkImage = createWaterMark1(watermarkText); byte[] imageData = new byte[watermarkImage.length()]; FileInputStream fis = new FileInputStream(watermarkImage); fis.read(imageData); ws.setWatermarkImage(imageData, width, height); wwb.write(); wwb.close(); fis.close(); }} ExcelUtil excelUtil = new ExcelUtil();excelUtil.addWatermark("水印测试"); 转载地址:http://ckxfk.baihongyu.com/