poi加密excel2007
- 本案例在springboot2.0+poi4.1环境下可正常运行,只支持excel2007以上版本(文件后缀为.xlsx)
pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>poiencrypt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>poiencrypt</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
示例代码:
public void download(HttpServletResponse response) throws IOException {
// 创建表格
SXSSFWorkbook wb = new SXSSFWorkbook();
SXSSFSheet sheet = wb.createSheet("sheet");
SXSSFRow row = sheet.createRow(0);
SXSSFCell cell = row.createCell(0);
cell.setCellValue("测试");
cell.setCellType(CellType.STRING);
SXSSFCell cell2 = row.createCell(1);
cell2.setCellValue(1231);
cell2.setCellType(CellType.NUMERIC);
// 将excel流临时存储
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write(baos);
baos.flush();
ByteArrayInputStream workbookInput = new ByteArrayInputStream(baos.toByteArray());
// 加密
try (POIFSFileSystem fs = new POIFSFileSystem()) {
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("123456");
try (OPCPackage opc = OPCPackage.open(workbookInput); OutputStream os = enc.getDataStream(fs)) {
opc.save(os);
} catch (InvalidFormatException | GeneralSecurityException e) {
e.printStackTrace();
}
// 输出
// Write out the encrypted version
response.reset();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode("加密文档", "UTF-8"));
fs.writeFilesystem(response.getOutputStream());
}
}
加密后效果: