首页 文章

Excel Headers 不可编辑的poi

提问于
浏览
0

我想使用poi使我的excel的 Headers 行不可编辑 .

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

在我的情况下,因为excel只包含 Headers ,其余的行将由用户填写我不能使整个表不可编辑,我只是希望 Headers 是用户无法编辑的 . 我怎样才能做到这一点?

1 回答

  • 0

    使用 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 (样式)来实现 .

    结果:除第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();
     }
    }
    

相关问题