简体   繁体   English

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

[英]Apache POI lock the cell but allow column resize

I create an Excel file through Apache POI XSSF and I lock the sheet with a password so user can't change the value of the first two row and first five columns (I lock the sheet and allowed editing of other cells).我通过Apache POI XSSF创建了一个 Excel 文件,并使用密码锁定了工作表,因此用户无法更改前两行和前五列的值(我锁定工作表并允许编辑其他单元格)。 All work fine, the only problem is that the user can't resize the column so he can neither change nor resize the columns to read all the cells value.一切正常,唯一的问题是用户无法调整列的大小,因此他既不能更改也不能调整列的大小来读取所有单元格的值。 Is it possible to allow column resize even if the sheet is protected?即使工作表受到保护,是否可以允许调整列大小? Thi is my configuration这是我的配置

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

I read about lockFormatCell() but I don't understand if it can help me.我阅读了有关lockFormatCell()的信息,但我不明白它是否可以帮助我。 Thanks谢谢

To be able resizing the column size while sheet is protected, you will need setting XSSFSheet.lockFormatColumns to false .为了能够在工作表受到保护时调整列大小,您需要将XSSFSheet.lockFormatColumns设置为false

Complete example:完整示例:

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

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

 }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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