简体   繁体   中英

How to lock only cell content in Excel sheet

I am working on exporting some data to Excel using Java POI library. Some of the cells in this data have to be read-only. I make it by:

CellStyle lockedCell = workbook.createCellStyle();
lockedCell.setLocked(true);
cell.setCellStyle(lockedCell);

and after it:

workbook.getSheetAt(workbook.getActiveSheetIndex()).protectSheet("");

It works quite well, but there is one problem - I cannot modify the width of columns containing locked cells.

Is it possible to lock only the content of the cells, so that I could modify columns width?

I do not think that it is possible to only allow user-width-modifications on locked cells.

What you can do instead is, after populating the data, call autoSizeColumn(colNumber); on the sheet for each column populated.

int colMaxLength = workbook.getActiveSheetIndex().getRow(0).getLastCellNum();
HSSFSheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
for(int i = 0 ; i < colMaxLength ; i++){
   activeSheet.autoSizeColumn(i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM