When you think about it though if you are trying to automate the generation of password protected Excel files you will need to store somewhere the password you are using to encrypt the workbook (Granted you are supposed to store that encrypted as well) so a workaround for the issue would be to store not only the password but also an empty Excel Workbook protected with that same password. POI does allow to access a Password Protected File so you can load the protected empty workbook and do all manipulations on it. The result will be an Excel file which holds the expected encrypted content.
On the other hand POI supports Write Password Protection. So if that is what you are looking for then this code will do the trick:
package com.nestorurquiza.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class XlsUtil {
public static void passwordProtect( InputStream is, OutputStream os, String password ) throws IOException {
HSSFWorkbook targetWorkbook = new HSSFWorkbook(is);
int numberOfSheets = targetWorkbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
HSSFSheet sheet = targetWorkbook.getSheetAt(i);
sheet.protectSheet(password);
}
targetWorkbook.write(os);
}
public static void main(String arg[]) {
try{
InputStream is = (new FileInputStream("/Users/nestor/Downloads/unprotected.xls"));
FileOutputStream os =new FileOutputStream(new File("/Users/nestor/Downloads/protected.xls"));
passwordProtect(is, os, "testPassword");
os.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment