如何在Java中密码保护压缩的Excel文件?

我有一个密码保护Excel文件的问题。

情况是,我有一个zip文件,里面有一个Excel文件。 我需要编写一个Java程序,以密码保护Excel文件。 因此,用户应该能够解压文件(zip文件不需要密码保护)。 但是,Excel需要密码保护。 当用户试图解压文件时,他应该可以这样做。 当他试图打开Excel文件(在解压缩的文件夹内)时,它必须要求input密码。 问题类似于用java保护excel文件,增加了复杂性,Excel文件被压缩。

我有代码,密码保护只有压缩文件,但这不是我想要的。

import java.io.File; import java.util.ArrayList; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.util.Zip4jConstants; /** * Demonstrates adding files to zip file with standard Zip Encryption */ public class AddFilesWithStandardZipEncryption { public AddFilesWithStandardZipEncryption() { try { // Initiate ZipFile object with the path/name of the zip file. //ZipFile zipFile = new ZipFile("c:\\ZipTest\\AddFilesWithStandardZipEncryption.zip"); ZipFile zipFile = new ZipFile("C:\\homepage\\workspace\\PasswordProtectedFiles\\new.zip"); // Build the list of files to be added in the array list // Objects of type File have to be added to the ArrayList ArrayList filesToAdd = new ArrayList(); //filesToAdd.add(new File("C:\\homepage\\workspace\\passwordprotectedzipfile\\profile\\profile.txt")); filesToAdd.add(new File("C:\\homepage\\workspace\\PasswordProtectedFiles\\new.xlsx")); //filesToAdd.add(new File("c:\\ZipTest\\myvideo.avi")); //filesToAdd.add(new File("c:\\ZipTest\\mysong.mp3")); // Initiate Zip Parameters which define various properties such // as compression method, etc. ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to store compression // Set the compression level parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // Set the encryption flag to true // If this is set to false, then the rest of encryption properties are ignored parameters.setEncryptFiles(true); // Set the encryption method to Standard Zip Encryption parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // Set password parameters.setPassword("test123!"); // Now add files to the zip file // Note: To add a single file, the method addFile can be used // Note: If the zip file already exists and if this zip file is a split file // then this method throws an exception as Zip Format Specification does not // allow updating split zip files zipFile.addFiles(filesToAdd, parameters); } catch (ZipException e) { e.printStackTrace(); } } public static void main(String[] args) { new AddFilesWithStandardZipEncryption(); } } 

没有解压,就不可能密码保护在zip文件里面的excel。

这是你可以做的

  • 使用提示解压缩内容什么是使用Java提取压缩文件的最佳方式? 使用Java API压缩和解压缩数据
  • 使用密码保护的Excel文件中的提示密码保护提取的Excel文件
  • 使用Java Compress Large File中的提示来压缩密码保护的excel文件
  • 使用java.util.zip或zip4j将文件解压缩到一些临时目录或内存,如果你知道它很小。
  • 然后使用Apache POI库中的HSSFWorkbook.writeProtectWorkbook
  • 再次压缩Excel工作簿。

我想你应该检查出truezip( Truezip网站 )。 它提供对ZIP,JAR,EAR,WAR等的读/写访问,并支持附加到现有的ZIP文件。

我build议你创build一个没有excel文件的压缩文件,在你提供的链接中创build你的passworded excel文件,然后使用truezip将这个excel文件写入压缩文件。 希望这可以帮助