问题
I am trying to read an excel sheet of data, I am able to get the data and read it using HSSFWorkbook
Everything works well, I am able to get the data.
I have set a password for the workbook, manually in the excel sheet Protect Workbook
to "ABCXYZ" and while opening the excel file it will ask me the password and only after the password in correct it lets me in to write or read the excel file.
My question is how to get this password "ABCXYZ" in the java program.
HSSFWorkbook wb = new HSSFWorkbook(inputStream);
wb.isWriteProtected();--> This returns false.
回答1:
As far as I know, you can use:
(in Excel 2003)
POIFSFileSystem pfs = new POIFSFileSystem(new FileInputStream("yourexcelfile.xls"));
Biff8EncryptionKey.setCurrentUserPassword("ABCXYZ");
HSSFWorkbook wb = new HSSFWorkbook(pfs);
(in 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));
Hope it helps!
回答2:
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) {
}
来源:https://stackoverflow.com/questions/18407725/get-the-excel-workbook-password-using-apache-poi