[英]How to password protect a zipped Excel file in Java?
我有一個密碼保護Excel文件的問題。
情況是,我有一個zip文件,其中有一個Excel文件。 我需要編寫一個Java程序,以密碼保護Excel文件。 因此,用戶應該能夠解壓縮文件(壓縮文件不需要密碼保護)。 但是,Excel需要使用密碼保護。 當用戶嘗試解壓縮文件時,他應該能夠解壓縮。 當他嘗試打開Excel文件(位於解壓縮的文件夾內)時,它必須要求輸入密碼。 問題類似於使用java保護excel文件 ,但增加了壓縮Excel文件的復雜性。
我有代碼,該密碼僅保護zip文件,但這不是我想要的。
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。
這是你可以做的
我認為您應該查看truezip( Truezip網站 )。 它提供對ZIP,JAR,EAR,WAR等的讀/寫訪問權限,並支持附加到現有的ZIP文件。
建議您創建不包含excel文件的zip文件,按照您提供的鏈接中的說明創建密碼的excel文件,然后使用truezip將此excel文件寫入存檔。 希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.