簡體   English   中英

使用Java讀取受密碼保護的Excel文件(.xlsx)

[英]Read Password protected excel file(.xlsx) using Java

我嘗試了以下代碼,

import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("D://protectedfile.xlsx"));
    EncryptionInfo info = new EncryptionInfo(fs);
    Decryptor d = new Decryptor(info); //Error
    d.verifyPassword(Decryptor.DEFAULT_PASSWORD);

它引發錯誤編譯錯誤: Cannot instantiate the type Decryptor

但是最終,這種方法將需要我復制並創建新的工作簿,以便在其中讀取數據。

  1. 為什么我無法實例化Decryptor?
  2. 除此之外,還有什么其他方法,這樣我可以簡單地讀取受密碼保護的excel文件,而無需創建它的副本

注意:我看過這篇閱讀excel文件的文章 ,但對我的實際情況沒有幫助

啊,我發現了你的問題。 是這行:

Decryptor d = new Decryptor(info);

Apache POI加密文檔所示 ,該行需要

Decryptor d = Decryptor.getInstance(info);

建議您閱讀有關加密的POI文檔 ,並確保您使用的是最新版本的Apache POI(撰寫本文時為3.11 beta 2)

另外, 根據文檔 ,不建議從InputStream打開文件 ,因為它速度較慢且內存較高(所有內容都必須緩沖)。 相反,您的代碼實際上應該是:

NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("D://protectedfile.xlsx"));
EncryptionInfo info = new EncryptionInfo(fs);
Decryptor d = Decryptor.getInstance(info);
if (d.verifyPassword("password")) {
   XSSFWorkbook wb = new XSSFWorkbook(d.getDataStream(fs));
} else {
   // Password is wrong
}

最后,獲取解密的數據,並將其傳遞給XSSFWorkbook以讀取加密的工作簿

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM