需要一些前置知识(一些基本知识)
导出excel带水印:前置知识1 BufferedImage和ImageIO
导出excel带水印:前置知识2 Graphics2D用法
导出excel带水印:前置知识3 ByteArrayOutputStream
导出excel带水印:前置知识4 BigExcelWriter
导出excel带水印:前置知识5 POI包
前端代码就不贴,直接看页面
开始看后端代码
搜索类NjryTaskInfoQueryCriteria
package com.njry.sjzl.busi.domain.vo;
import lombok.Data;
import java.util.Set;
/**
* @author wj
* @date 2024-04-25
**/
@Data
public class NjryTaskInfoQueryCriteria{
private String taskId;
private String searchTaskId;
private String taskName;
private Integer taskType;
private String procName;
private Integer startTime;
private String createOperator;
private Set<String> taskSet;
}
实体类NjryTaskInfo
package com.njry.sjzl.busi.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiModelProperty;
import cn.hutool.core.bean.copier.CopyOptions;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
/**
* @description /
* @author wj
* @date 2024-04-25
**/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("NJRY_TASK_INFO")
public class NjryTaskInfo implements Serializable {
@NotNull(groups = WorkTypeBaseEntity.Update.class)
@TableId(value="task_id", type = IdType.INPUT)
// @TableField(exist = false)
@ApiModelProperty(value = "ID", hidden = true)
private Long id;
@ApiModelProperty(value = "任务编号")
private String taskId;
@NotEmpty(message = "任务名称不能为空")
@Length(min = 1 , max = 80 , message = "名字字节长度1~80")
@ApiModelProperty(value = "任务名称")
private String taskName;
@NotNull
@ApiModelProperty(value = "任务类型 1:日 2:月 3:实时")
private Integer taskType;
@NotEmpty(message = "存储过程名称不能为空")
@Length(min = 1 , max = 40 , message = "名字字节长度1~40")
@ApiModelProperty(value = "存储过程名称")
private String procName;
@NotNull
@ApiModelProperty(value = "开始检测时间")
private Integer startTime;
@ApiModelProperty(value = "是否有效")
private Integer isValid;
@NotNull
@ApiModelProperty(value = "手机号码")
private String cellphone;
@ApiModelProperty(value = "结束日期")
private Date endDate;
@NotNull
@ApiModelProperty(value = "开始日期")
private Date startDate;
@ApiModelProperty(value = "是否发送成功短信")
private Integer isSucMes;
@NotNull
@TableField(exist = false)
@ApiModelProperty(value = "参数信息列表")
private List<NjryTaskArg> njryTaskArgs;
@TableField(exist = false)
@ApiModelProperty(value = "依赖列表")
private List<NjryTaskRelation> dependenceNjryTasks;
public void copy(NjryTaskInfo source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
controller层(没有贴引用)
/**
* @author wj
* @date 2024-04-25
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "任务管理管理")
@RequestMapping("/api/njryTaskInfo")
public class NjryTaskInfoController {
private final NjryTaskInfoService njryTaskInfoService;
private static final String ENTITY_NAME = "njry_task_info";
@Log("导出数据")
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('njryTaskInfo:list')")
public void exportNjryTaskInfo(HttpServletResponse response, NjryTaskInfoQueryCriteria criteria) throws IOException {
njryTaskInfoService.download(njryTaskInfoService.queryAll(criteria), response);
}
}
service层(没有贴引用)
public interface NjryTaskInfoService extends IService<NjryTaskInfo> {
/**
* 查询所有数据不分页
* @param criteria 条件参数
* @return List<NjryTaskInfoDto>
*/
List<NjryTaskInfo> queryAll(NjryTaskInfoQueryCriteria criteria);
/**
* 导出数据
* @param all 待导出的数据
* @param response /
* @throws IOException /
*/
void download(List<NjryTaskInfo> all, HttpServletResponse response) throws IOException;
}
impl层(没有贴引用,但这里用了一个非常重要的工具类FileUtil)
/**
* @description 服务实现
* @author wj
* @date 2024-04-25
**/
@Service
@RequiredArgsConstructor
public class NjryTaskInfoServiceImpl extends ServiceImpl<NjryTaskInfoMapper, NjryTaskInfo> implements NjryTaskInfoService {
private final NjryTaskInfoMapper njryTaskInfoMapper;
@Override
public List<NjryTaskInfo> queryAll(NjryTaskInfoQueryCriteria criteria){
return njryTaskInfoMapper.findAll(criteria);
}
@Override
public void download(List<NjryTaskInfo> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (NjryTaskInfo njryTaskInfo : all) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("任务编号", njryTaskInfo.getTaskId());
map.put("任务名称", njryTaskInfo.getTaskName());
map.put("任务类型 1:日 2:月 3:实时", njryTaskInfo.getTaskType());
map.put("存储过程名称", njryTaskInfo.getProcName());
map.put("开始检测时间", njryTaskInfo.getStartTime());
map.put("是否有效", njryTaskInfo.getIsValid());
map.put("手机号码", njryTaskInfo.getCellphone());
map.put("任务创建日期", njryTaskInfo.getCreateDate());
map.put("任务创建人编号", njryTaskInfo.getCreateOperator());
map.put("修改日期", njryTaskInfo.getModifyDate());
map.put("修改人编号", njryTaskInfo.getModifyOperator());
map.put("结束日期", njryTaskInfo.getEndDate());
map.put("开始日期", njryTaskInfo.getStartDate());
map.put("是否发送成功短信", njryTaskInfo.getIsSucMes());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}
mapper层
@Mapper
public interface NjryTaskInfoMapper extends BaseMapper<NjryTaskInfo> {
List<NjryTaskInfo> findAll(@Param("criteria") NjryTaskInfoQueryCriteria criteria);
}
xml
<select id="findAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from NJRY_TASK_INFO
<where>
<if test="criteria.taskId != null and criteria.taskId != ''">
and task_id = #{criteria.taskId}
</if>
<if test="criteria.createOperator != null and criteria.createOperator != ''">
and CREATE_OPERATOR = #{criteria.createOperator}
</if>
<if test="criteria.taskName != null">
and TASK_NAME like concat('%'||#{criteria.taskName},'%')
</if>
<if test="criteria.taskType != null">
and TASK_TYPE = #{criteria.taskType}
</if>
<if test="criteria.procName != null">
and PROC_NAME like concat('%'||#{criteria.procName},'%')
</if>
<if test="criteria.startTime != null">
and START_TIME = #{criteria.startTime}
</if>
</where>
</select>
回到impl层的导出download
暂时数据写差不多,就看水印怎么添加了(这里测试write.flush)
暂时数据写差不多,就看水印怎么添加了(结束测试,证明write.flush的重要性)
所有的准备都是为了看懂下面这两个工具类(重点)
工具类FileUtil
/*
*
*/
package com.njry.utils;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.njry.exception.BadRequestException;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* File工具类,扩展 hutool 工具包
*
* @author njry
* @date 2024-05-11
*/
public class FileUtil extends cn.hutool.core.io.FileUtil {
private static final Logger log = LoggerFactory.getLogger(FileUtil.class);
/**
* 系统临时目录
* <br>
* windows 包含路径分割符,但Linux 不包含,
* 在windows \\==\ 前提下,
* 为安全起见 同意拼装 路径分割符,
* <pre>
* java.io.tmpdir
* windows : C:\Users/xxx\AppData\Local\Temp\
* linux: /temp
* </pre>
*/
public static final String SYS_TEM_DIR = System.getProperty("java.io.tmpdir") + File.separator;
/**
* 定义GB的计算常量
*/
private static final int GB = 1024 * 1024 * 1024;
/**
* 定义MB的计算常量
*/
private static final int MB = 1024 * 1024;
/**
* 定义KB的计算常量
*/
private static final int KB = 1024;
/**
* 格式化小数
*/
private static final DecimalFormat DF = new DecimalFormat("0.00");
public static final String IMAGE = "图片";
public static final String TXT = "文档";
public static final String MUSIC = "音乐";
public static final String VIDEO = "视频";
public static final String OTHER = "其他";
/**
* MultipartFile转File
*/
public static File toFile(MultipartFile multipartFile) {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix = "." + getExtensionName(fileName);
File file = null;
try {
// 用uuid作为文件名,防止生成的临时文件重复
file = new File(SYS_TEM_DIR + IdUtil.simpleUUID() + prefix);
// MultipartFile to File
multipartFile.transferTo(file);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return file;
}
/**
* 获取文件扩展名,不带 .
*/
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
/**
* Java文件操作 获取不带扩展名的文件名
*/
public static String getFileNameNoEx(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length()))) {
return filename.substring(0, dot);
}
}
return filename;
}
/**
* 文件大小转换
*/
public static String getSize(long size) {
String resultSize;
if (size / GB >= 1) {
//如果当前Byte的值大于等于1GB
resultSize = DF.format(size / (float) GB) + "GB ";
} else if (size / MB >= 1) {
//如果当前Byte的值大于等于1MB
resultSize = DF.format(size / (float) MB) + "MB ";
} else if (size / KB >= 1) {
//如果当前Byte的值大于等于1KB
resultSize = DF.format(size / (float) KB) + "KB ";
} else {
resultSize = size + "B ";
}
return resultSize;
}
/**
* inputStream 转 File
*/
static File inputStreamToFile(InputStream ins, String name){
File file = new File(SYS_TEM_DIR + name);
if (file.exists()) {
return file;
}
OutputStream os = null;
try {
os = new FileOutputStream(file);
int bytesRead;
int len = 8192;
byte[] buffer = new byte[len];
while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
CloseUtil.close(os);
CloseUtil.close(ins);
}
return file;
}
/**
* 将文件名解析成文件的上传路径
*/
public static File upload(MultipartFile file, String filePath) {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS");
// 过滤非法文件名
String name = getFileNameNoEx(verifyFilename(file.getOriginalFilename()));
String suffix = getExtensionName(file.getOriginalFilename());
String nowStr = "-" + format.format(date);
try {
String fileName = name + nowStr + "." + suffix;
String path = filePath + fileName;
// getCanonicalFile 可解析正确各种路径
File dest = new File(path).getCanonicalFile();
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
if (!dest.getParentFile().mkdirs()) {
System.out.println("was not successful.");
}
}
// 文件写入
file.transferTo(dest);
return dest;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* 导出excel
*/
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
FileInputStream watermarkFileInput = null;
FileInputStream tempInput = null;
try{
String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".tmp.xlsx";
String watermarkPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";
File file = new File(tempPath);
BigExcelWriter writer = ExcelUtil.getBigWriter(file);
// 一次性写出内容,使用默认样式,强制输出标题
writer.write(list, true);
SXSSFSheet sheet = (SXSSFSheet)writer.getSheet();
//上面需要强转SXSSFSheet 不然没有trackAllColumnsForAutoSizing方法
sheet.trackAllColumnsForAutoSizing();
//列宽自适应
writer.autoSizeColumnAll();
// 写出到文件(不写到文件,下面xSSFWorkbook就拿不到导出的数据)
writer.flush();
File tempFile = new File(tempPath);
tempInput = new FileInputStream(tempFile);
XSSFWorkbook xSSFWorkbook = new XSSFWorkbook(tempInput);
// 将导出的数据加水印放到另一个文件watermarkPath里面
// sheet.getWorkbook().getXSSFWorkbook(),不知道这里是不是没获取到上面数据写入后的XSSFWorkbook
PoiSecurity.addWatermarkToXlsx(new String[]{"test"},xSSFWorkbook,new File(watermarkPath));
xSSFWorkbook.close();
tempInput.close();
// 终止后删除临时文件
tempFile.deleteOnExit();
//response为HttpServletResponse对象
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");
ServletOutputStream out = response.getOutputStream();
File watermarkFile = new File(watermarkPath);
watermarkFileInput = new FileInputStream(watermarkFile);
IOUtils.copy(watermarkFileInput,out);
watermarkFile.deleteOnExit();
watermarkFileInput.close();
//此处记得关闭输出Servlet流
IoUtil.close(out);
}finally {
if(watermarkFileInput!=null){
watermarkFileInput.close();
}
if(tempInput!=null){
tempInput.close();
}
}
}
public static String getFileType(String type) {
String documents = "txt doc pdf ppt pps xlsx xls docx";
String music = "mp3 wav wma mpa ram ra aac aif m4a";
String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg";
String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg";
if (image.contains(type)) {
return IMAGE;
} else if (documents.contains(type)) {
return TXT;
} else if (music.contains(type)) {
return MUSIC;
} else if (video.contains(type)) {
return VIDEO;
} else {
return OTHER;
}
}
public static void checkSize(long maxSize, long size) {
// 1M
int len = 1024 * 1024;
if (size > (maxSize * len)) {
throw new BadRequestException("文件超出规定大小:" + maxSize + "MB");
}
}
/**
* 判断两个文件是否相同
*/
public static boolean check(File file1, File file2) {
String img1Md5 = getMd5(file1);
String img2Md5 = getMd5(file2);
if(img1Md5 != null){
return img1Md5.equals(img2Md5);
}
return false;
}
/**
* 判断两个文件是否相同
*/
public static boolean check(String file1Md5, String file2Md5) {
return file1Md5.equals(file2Md5);
}
private static byte[] getByte(File file) {
// 得到文件长度
byte[] b = new byte[(int) file.length()];
InputStream in = null;
try {
in = new FileInputStream(file);
try {
System.out.println(in.read(b));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
} finally {
CloseUtil.close(in);
}
return b;
}
private static String getMd5(byte[] bytes) {
// 16进制字符
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(bytes);
byte[] md = mdTemp.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
// 移位 输出字符串
for (byte byte0 : md) {
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* 下载文件
*
* @param request /
* @param response /
* @param file /
*/
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) {
response.setCharacterEncoding(request.getCharacterEncoding());
response.setContentType("application/octet-stream");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
IOUtils.copy(fis, response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (fis != null) {
try {
fis.close();
if (deleteOnExit) {
file.deleteOnExit();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
/**
* 验证并过滤非法的文件名
* @param fileName 文件名
* @return 文件名
*/
public static String verifyFilename(String fileName) {
// 过滤掉特殊字符
fileName = fileName.replaceAll("[\\\\/:*?\"<>|~\\s]", "");
// 去掉文件名开头和结尾的空格和点
fileName = fileName.trim().replaceAll("^[. ]+|[. ]+$", "");
// 不允许文件名超过255(在Mac和Linux中)或260(在Windows中)个字符
int maxFileNameLength = 255;
if (System.getProperty("os.name").startsWith("Windows")) {
maxFileNameLength = 260;
}
if (fileName.length() > maxFileNameLength) {
fileName = fileName.substring(0, maxFileNameLength);
}
// 过滤掉控制字符
fileName = fileName.replaceAll("[\\p{Cntrl}]", "");
// 过滤掉 ".." 路径
fileName = fileName.replaceAll("\\.{2,}", "");
// 去掉文件名开头的 ".."
fileName = fileName.replaceAll("^\\.+/", "");
// 保留文件名中最后一个 "." 字符,过滤掉其他 "."
fileName = fileName.replaceAll("^(.*)(\\.[^.]*)$", "$1").replaceAll("\\.", "") +
fileName.replaceAll("^(.*)(\\.[^.]*)$", "$2");
return fileName;
}
public static String getMd5(File file) {
return getMd5(getByte(file));
}
}
工具类PoiSecurity
package com.njry.utils;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import javax.imageio.ImageIO;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionInfoBuilder;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.crypt.binaryrc4.BinaryRC4EncryptionInfoBuilder;
import org.apache.poi.poifs.crypt.binaryrc4.BinaryRC4Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class PoiSecurity {
public static void addWatermarkToXlsx(String[] content,XSSFWorkbook xssfworkbook,File outfile) throws IOException{
ByteArrayOutputStream bytestream = createWaterMark(content);
// XSSFWorkbook下面有几个sheet
int sheetsize = xssfworkbook.getNumberOfSheets();
for(int index=0;index<sheetsize;index++){
XSSFSheet sheet = xssfworkbook.getSheetAt(index);
XSSFWorkbook workbook = sheet.getWorkbook();
// bytestream.toByteArray()(前置知识)
// 下面这一串看不懂(没看官网文档的下场)
int pictureIdx = workbook.addPicture(bytestream.toByteArray(), Workbook.PICTURE_TYPE_PNG);
POIXMLDocumentPart poixmlDocumentPart = workbook.getAllPictures().get(pictureIdx);
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());
}
if(!outfile.exists()){
File par = outfile.getParentFile();
if(!par.exists()){
par.mkdirs();
}
outfile.createNewFile();
}
FileOutputStream out = new FileOutputStream(outfile);
xssfworkbook.write(out);
out.close();
}
private static ByteArrayOutputStream createWaterMark(String[] content) throws IOException {
int width = 250;
int height = 200;
// (前置知识)
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 获取bufferedImage对象
String fontType = "宋体";
int fontStyle = java.awt.Font.BOLD;
int fontSize = 20;
// 设置字体(前置知识)
java.awt.Font font = new java.awt.Font(fontType, fontStyle, fontSize);
Graphics2D g2d = image.createGraphics(); // 获取Graphics2d对象(前置知识)
// 这里实在看不懂,为啥销毁后用BufferedImage重新获取Graphics2d对象
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
g2d.setColor(new java.awt.Color(0, 0, 0, 40));//设置字体颜色和透明度,最后一个参数为透明度(前置知识)
g2d.setStroke(new BasicStroke(1)); // 设置字体
g2d.setFont(font); // 设置字体类型 加粗 大小
g2d.rotate(-0.5, (double) image.getWidth() / 2, (double) image.getHeight() / 2);//设置倾斜度
// 要想得到表示屏幕设备字体属性的对象(前置知识)
FontRenderContext context = g2d.getFontRenderContext();
// 循环设置水印文字位置(看不懂)
for (int i = 0; i < content.length; i++) {
// 返回包围字符串的矩形(前置知识)
Rectangle2D bounds = font.getStringBounds(content[i], context);
// 宽度
double x = (width - bounds.getWidth()) / 2;
// 高度
double y = (height - bounds.getHeight()) / 2;
// 上坡度
double ascent = -bounds.getY();
double baseY = y + ascent;
// 写入水印文字原定高度过小,所以累计写水印,增加高度
g2d.drawString(content[i], (int) x, (int) baseY+(30*i));
}
// 设置透明度(前置知识)
// g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_OVER));
// 释放对象
g2d.dispose();
// ByteArrayOutputStream(前置知识)
ByteArrayOutputStream os = new ByteArrayOutputStream();
// BufferedImage –> byte[](前置知识)
ImageIO.write(image, "png", os);
return os;
}
public static void encXlsx(String paasword,File file) throws InvalidFormatException, IOException, GeneralSecurityException{
try (POIFSFileSystem fs = new POIFSFileSystem()) {
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
// EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes192, HashAlgorithm.sha384, -1, -1, null);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(paasword);
// Read in an existing OOXML file and write to encrypted output stream
// don't forget to close the output stream otherwise the padding bytes aren't added
try (OPCPackage opc = OPCPackage.open(file, PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs)) {
opc.save(os);
}
// Write out the encrypted version
try (FileOutputStream fos = new FileOutputStream(file)) {
fs.writeFilesystem(fos);
}
}
}
}