首页 文章

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

提问于
浏览
0

我通过 Apache POI XSSF 创建一个Excel文件,然后我用密码锁定工作表,这样用户就可以调整列的大小,这样他既不能更改也不能调整列的大小以读取所有单元格的值 . 即使工作表受到保护,是否可以允许列调整大小?这是我的配置

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() 但我不明白它是否可以帮助我 . 谢谢

1 回答

  • 2

    为了能够在工作表受到保护时调整列大小,您需要将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();
    
     }
    
    }
    

相关问题