Java – use Apache POI to make columns read-only

I am using Apache POI to generate Excel files I need to make column 4 read-only, and the other 2 columns will be edited by the user

I'm using xssf cellstyle to achieve this goal, but it doesn't work for me

The whole code is:

Map<String,XSSFCellStyle> styles = new HashMap<String,XSSFCellStyle>();

XSSFCellStyle style5 = wb.createCellStyle();
XSSFFont headerFont = wb.createFont();
headerFont.setBold(true);
style5.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style5.setFillPattern(XSSFCellStyle.soLID_FOREGROUND);
style5.setFont(headerFont);
style5.setLocked(true); // this line does not get executed.
styles.put("header",style5);

Solution

You must protect the entire worksheet and unlock cells that should be editable:

String file = "c:\\poitest.xlsx";
FileOutputStream outputStream = new FileOutputStream(file);
Workbook wb = new XSSFWorkbook();

CellStyle unlockedCellStyle = wb.createCellStyle();
unlockedCellStyle.setLocked(false);

Sheet sheet = wb.createSheet();
sheet.protectSheet("password");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("TEST");
cell.setCellStyle(unlockedCellStyle);

wb.write(outputStream);
outputStream.close();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>