使用Apache POI在Excel中锁定单个列

时间:2021-05-18 20:24:10

I want to create a Excel in which only a specific column is locked(Read-only), and the rest are editable,

我想创建一个只有特定列被锁定(只读)的Excel,其余的都是可编辑的,

I am using the following approach, but that doesn't seem to work.

我使用的是下面的方法,但似乎行不通。

Create two CellStyles, one with setLocked(true) and other with setLocked(false).

创建两个CellStyles,一个是setlock (true),另一个是setlock (false)。

Then apply the locked style for all the cells in the column which needs to be locked, and the unlocked style for all the other cells.

然后在需要锁定的列中应用锁定的样式,以及所有其他单元格的解锁样式。

Protect the sheet using sheet.protectSheet("");

使用sheet. protectsheet("")保护纸张;

But when I open the created Excel in open office, I notice that all the cells are locked!

但是当我在open office中打开创建的Excel时,我注意到所有的单元格都被锁定了!

None of them are editable.

没有一个是可编辑的。

How can I achieve the above requirement?

我怎样才能达到上述要求?

P.S : I cant use the data validation approach.

P。S:我不能使用数据验证方法。

1 个解决方案

#1


21  

If you do the opposite it works. Protect the whole sheet and call setLocked(false) for the cells which should be editable.

如果你反其道而行之,它就会奏效。保护整个表,并为应该可编辑的单元格调用setLocked(false)。

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();

#1


21  

If you do the opposite it works. Protect the whole sheet and call setLocked(false) for the cells which should be editable.

如果你反其道而行之,它就会奏效。保护整个表,并为应该可编辑的单元格调用setLocked(false)。

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();