Apache POI 锁定单元格但允许调整列大小

Apache POI lock the cell but allow column resize

我通过 Apache POI XSSF 创建了一个 Excel 文件并用密码锁定了 sheet 这样用户就无法更改前两行和前五列的值(我锁定 sheet 并允许编辑其他单元格)。一切正常,唯一的问题是用户无法调整列的大小,因此他既不能更改也不能调整列的大小来读取所有单元格的值。 即使 sheet 受到保护,是否也可以允许调整列大小? 这是我的配置

workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Sheet1");
sheet.protectSheet("passwordExcel"); 
unlockedNumericStyle = workbook.createCellStyle(); 
unlockedNumericStyle.setLocked(false);
// Format cell for date
dateStyle = workbook.createCellStyle();
CreationHelper createHelper = workbook.getCreationHelper();
dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
sheet.autoSizeColumn(1);

我阅读了有关 lockFormatCell() 的内容,但我不明白它是否对我有帮助。谢谢

要在 sheet 受保护时调整列大小,您需要将 XSSFSheet.lockFormatColumns 设置为 false

完整示例:

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

public class CreateExcelXSSFProtectedSheet {

 public static void main(String[] args) throws Exception {

  Workbook workbook = new XSSFWorkbook();

  CreationHelper createHelper = workbook.getCreationHelper();

  CellStyle unlockedNumericStyle = workbook.createCellStyle();
  unlockedNumericStyle.setDataFormat(createHelper.createDataFormat().getFormat("$#,##0.00_);[Red]($#,##0.00)"));
  unlockedNumericStyle.setLocked(false);

  CellStyle dateStyle = workbook.createCellStyle();
  dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));

  Sheet sheet = workbook.createSheet();

  Row row = sheet.createRow(0);
  Cell cell = row.createCell(1);
  cell.setCellValue("some data");

  row = sheet.createRow(1);
  cell = row.createCell(1);
  cell.setCellValue(-123456789.0123456);
  cell.setCellStyle(unlockedNumericStyle);

  row = sheet.createRow(2);
  cell = row.createCell(1);
  cell.setCellValue(new java.util.Date());
  cell.setCellStyle(dateStyle);

  ((XSSFSheet)sheet).lockFormatColumns(false);

  sheet.protectSheet("passwordExcel"); 

  sheet.autoSizeColumn(1);

  workbook.write(new FileOutputStream("CreateExcelXSSFProtectedSheet.xlsx"));
  workbook.close();

 }

}