pom.xml 引入依赖
<!--水印-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>
//获取当前时间年月日
String calculateDate =DateUtil.formatDateTime(new Date());
try {
//添加水印内容为当前日期
//调用通用类,设置水印的格式
BufferedImage bufferImg = WaterMark.createWaterMark("xlgsm"+calculateDate);
// 导出到字节流B'
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferImg, "png", os);
File path = new File(ResourceUtils.getURL("classpath:").getPath());
String url = URLDecoder.decode(path.getAbsolutePath(), "utf-8");
//模板路径
FileInputStream fileInput = new FileInputStream(url+"/static/dist/download/XXXXXXXX.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fileInput);
fileInput.close();
int pictureIdx = wb.addPicture(os.toByteArray(), Workbook.PICTURE_TYPE_PNG);
POIXMLDocumentPart poixmlDocumentPart = wb.getAllPictures().get(pictureIdx);
//获取每个Sheet表
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
XSSFSheet sheet = wb.getSheetAt(i);
PackagePartName ppn = poixmlDocumentPart.getPackagePart().getPartName();
String relType = XSSFRelation.IMAGES.getRelation();
PackageRelationship pr = sheet.getPackagePart().addRelationship(ppn, TargetMode.INTERNAL, relType, null);
sheet.getCTWorksheet().addNewPicture().setId(pr.getId());
//sheet.protectSheet(pwd);
}
//创建输出流
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
//导出模板的名称
String fileName = java.net.URLEncoder.encode("导出模板", "UTF-8");
String disposition = "attachment; fileName="+fileName+".xlsx";
response.setHeader("Content-Disposition", disposition);
wb.write(out);
out.flush();
out.close();
wb.close();
} catch (IOException e) {
LogUtil.log(e.getMessage(),Level.ERROR,e);
}
/**
* 创建水印
*/
public class WaterMark {
//
public static BufferedImage createWaterMark(String content) {
Integer width = 450;
Integer height = 400;
// 获取bufferedImage对象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
String fontType = "宋体";
Integer fontStyle = Font.PLAIN;
Integer fontSize = 25;
Font font = new Font(fontType, fontStyle, fontSize);
// 获取Graphics2d对象
Graphics2D g2d = image.createGraphics();
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
//设置字体颜色和透明度
g2d.setColor(Color.lightGray);
// 设置字体
g2d.setStroke(new BasicStroke(1));
// 设置字体类型 加粗 大小
g2d.setFont(font);
g2d.shear(0.1,-0.4);
//设置倾斜度
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();
return image;
}
}