Sorry to say that I do not know why POI fails you in this context - although
I can confirm that I saw exactly the behaviour you describe - but I am able
to offer a workable solution, well a fix anyway.
I simply used Excel itself to create a workbook on which I specified that a
password was required to modify the contents. Currently, I am running Excel
2007 and so I used the Save As -> Excel Options -> General Options route to
get to the point where I could specify a password that would be required to
modify the file. Next, I simply used HWPF to open this 'template' and was
able successfully to insert a sheet and add cells to that sheet before
saving the file away again. Interestingly, HWPF preserved the settings that
stipulated a password was required to open the file even though the
isWriteProtected() method returned the value false. There is just one
caveat; the 'template' file must contain at least one sheet so you will need
to take additional care when getting and creating sheets.
Can I ask which version of Excel you are using? The reason I ask this is
that I do suspect the problem may be caused by modifications introduced to
the workbook/worksheet protection mechanisms when Excel 2007 was introduced
as I cannot imagine that no one has needed to write protect a workbook in
the past.
Yours
Mark B
susantaghosh wrote:
>
> Hi,
> Could anyone please help me to create a password protected excel sheet.
> The requirement is, password needs to be given to open an excel file. It
> will not open the excel file without password. I am using the following
> program, but it is not asking any password while opening.
> import java.io.;
> import org.apache.poi.hssf.usermodel.;
> class PasswordExcelSheet {
> public static void main(String arg[]) {
> try{
> FileOutputStream out = new
> FileOutputStream("D:\\java_prog\\excelsheet\\MyExcel.xls");
> HSSFWorkbook hssfworkbook = new HSSFWorkbook();
> hssfworkbook.writeProtectWorkbook("abc","xyz");
> HSSFSheet sheet = hssfworkbook.createSheet("new sheet");
> String s="HCL Tech";
> HSSFCellStyle cs = hssfworkbook.createCellStyle();
> HSSFDataFormat df = hssfworkbook.createDataFormat();
> HSSFFont f = hssfworkbook.createFont();
> HSSFFont f2 = hssfworkbook.createFont();
> cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
> HSSFRow row = sheet.createRow((short)0);
> HSSFCell cell = row.createCell((short)0);
> cell.setCellValue(s );
> cell.setCellStyle(cs);
> //sheet.protectSheet("xyz");
> hssfworkbook.write(out);
> out.close();
> }
> catch(Exception e){
> System.out.println("Error : "+e);
> }
> }
> }
>
--
View this message in context:
http://old.nabble.com/POI-3.6--writeProtectWorkbook%28%29-method-does-not-work-to-set-password-to-excel-file-tp27514350p27515079.html
Sent from the POI - User mailing list archive at Nabble.com.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]