【问题标题】:Excel headers uneditable poiExcel 标题不可编辑的 poi
【发布时间】:2017-07-13 16:56:37
【问题描述】:

我想使用 poi 使​​我的 Excel 的标题行不可编辑。

我在互联网上得到了各种解决方案,首先要执行sheet.protectSheet("password"),这最终使整个工作表无法编辑,然后遍历所有可编辑的单元格并将它们的 cellStyle 设置为cellStyle.setLocked(false)

在我的情况下,由于 excel 只包含标题,其余行将由用户填写,我无法使整个工作表不可编辑,我只希望用户无法编辑标题。我怎样才能做到这一点?

【问题讨论】:

  • “我只希望用户无法编辑标题。”:那么您将如何使用Excels GUI 来满足该要求?因为apache poi 不能做Excel 本身不能做的事情。
  • @Fabien 感谢您的编辑 :)

标签: excel apache-poi


【解决方案1】:

使用XSSF 可以实现以下目标:

CellStyle 设置为具有setLocked false 作为所有列的默认样式。这可以通过设置具有 min col 1 和 max col 16384 并设置了该样式的 org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol 元素来实现。

然后通过为该行设置 CustomFormat true 来取消使用该样式的第 1 行。因此它不会对所有列使用默认样式。额外设置 CellStyle 具有 setLocked true 作为该行的默认样式。这可以通过从该行获取 org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow 元素并在那里设置 CustomFormatS(style) 来实现。

结果:除第 1 行外,所有单元格均已解锁。

例子:

import java.io.*;

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

public class CreateExcelSheetProtectOnlyFirstRow {

 public static void main(String[] args) throws Exception {
  Workbook workbook = new XSSFWorkbook();

  //create a CellStyle having setLocked false
  CellStyle cellstyleUnprotect = workbook.createCellStyle();
  cellstyleUnprotect.setLocked(false);
  //create a CellStyle having setLocked true
  CellStyle cellstyleProtect = workbook.createCellStyle();
  cellstyleProtect.setLocked(true);

  Sheet sheet = workbook.createSheet("Sheet1");

  //set the CellStyle having setLocked false as the default style for all columns
  org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol cTCol = 
      ((XSSFSheet)sheet).getCTWorksheet().getColsArray(0).addNewCol();
  cTCol.setMin(1);
  cTCol.setMax(16384);
  cTCol.setWidth(12.7109375);
  cTCol.setStyle(cellstyleUnprotect.getIndex());

  Row row = sheet.createRow(0);

  //set CustomFormat true for that row
  //so it does not using the default style for all columns
  //and set the CellStyle having setLocked true as the default style for that row
  org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow cTRow = 
      ((XSSFRow)row).getCTRow();
  cTRow.setCustomFormat(true);
  cTRow.setS(cellstyleProtect.getIndex());

  for (int c = 0; c < 3; c++) {
   row.createCell(c).setCellValue("Header " + (c+1));
  }

  sheet.protectSheet("password");   // protect sheet

  workbook.write(new FileOutputStream("CreateExcelSheetProtectOnlyFirstRow.xlsx"));
  workbook.close();
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 2012-11-23
    • 2018-05-27
    相关资源
    最近更新 更多