Apache POI : creating unprotected cells by default

2019-09-06 02:29发布

问题:

When I am creating protected sheets using Apache POI, all cells are protected by default. I have to unlock each cell individually. Is it possible to protect a sheet will all cells unprotected by default (so that I protect only cells why I want).

(code used)

/*for sheet protection*/
sheet.protected("password");
/*creating style to unlock cell */
CellStyle unlockedCellStyle = workbook.createCellStyle();
unlockedCellStyle.setLocked(false);

/*applying unlock style to cell */  
cell.setCellStyle(unlockedCellStyle);

回答1:

It is not possible to have created cells default to unlocked; locked is the default. But you are on the right track by creating a CellStyle with locked set to false. Make sure that you set locked to false on any and all of your new CellStyle objects that you want to be unlocked. Additionally, Excel has a limit on the number of cell styles that can be created in a Workbook, so re-use your CellStyle object(s) with each Cell you create.



回答2:

It is possible to change default cell style in apache POI.
Instead of creating a new cell style for your cell if you had done getCellStyle() on your cell, this would have returned the default cell style, and you would be able to edit it,
according to this.

getCellStyle never returns null, in case of new cells it returns the default cell style.

So basically to edit default cell style of a cell, either do getCellStyle on a newly created cell or try this workbook.getCellStyleAt(0).
Refer to this for more details.