POI导出文件,设置密码
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.poifs.crypt.*;
import org.apache.poi.poifs.crypt.agile.AgileEncryptionInfoBuilder;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class ExcelEncryptionExample {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(true);
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello, World!");
String password = "password";
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(password);
OutputStream os = enc.getDataStream(fs);
workbook.write(os);
os.close();
String filePath = "path/to/your/encrypted/file.xlsx";
try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
fs.writeFilesystem(outputStream);
}
System.out.println("Encrypted Excel file exported successfully!");
}
}