使用Apache POI获取excel工作簿密码

时间:2013-08-23 16:33:34

标签: java excel apache-poi

我正在尝试阅读excel数据表,我能够获取数据并使用HSSFWorkbook读取它一切正常,我能够获取数据。

我已经为Excel工作簿设置了一个密码,在excel表Protect Workbook中手动设置为“ABCXYZ”,打开excel文件时它会询问我密码,只有在密码正确后才能让我进入写或读excel文件。

我的问题是如何在java程序中获取此密码“ABCXYZ”。

HSSFWorkbook wb = new HSSFWorkbook(inputStream);
wb.isWriteProtected();--> This returns false.

2 个答案:

答案 0 :(得分:2)

据我所知,您可以使用:

(在Excel 2003中)

POIFSFileSystem pfs = new POIFSFileSystem(new FileInputStream("yourexcelfile.xls")); 
Biff8EncryptionKey.setCurrentUserPassword("ABCXYZ"); 
HSSFWorkbook wb = new HSSFWorkbook(pfs);

(在Excel 2007中)

POIFSFileSystem pfs = newPOIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("yourexcelfile.xlsx")); 
EncryptionInfo encInfo = new EncryptionInfo(pfs); 
Decryptor decryptor = new Decryptor(encInfo); 
decryptor.verifyPassword("ABCXYZ"); 
XSSFWorkbook wb = new XSSFWorkbook(decryptor.getDataStream(pfs));

希望它有所帮助!

答案 1 :(得分:1)

    try {           

        FileInputStream fileInput = new FileInputStream("sample.xls");         
        BufferedInputStream bufferInput = new BufferedInputStream(fileInput);            
        POIFSFileSystem poiFileSystem = new POIFSFileSystem(bufferInput);            

        Biff8EncryptionKey.setCurrentUserPassword("password");            
        HSSFWorkbook workbook = new HSSFWorkbook(poiFileSystem, true);            
        HSSFSheet sheet = workbook.getSheetAt(0);           

        HSSFRow row = sheet.createRow(0);
        Cell cell = row.createCell(0);

        cell.setCellValue("Hello World"); 

        FileOutputStream fileOut = new FileOutputStream(fname);
        workbook.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), "");
        workbook.write(fileOut);



    } catch (Exception ex) {



    }