2017-07-13 48 views
0

poiを使用して私のExcelのヘッダー行を編集不可能にしたいと考えています。Excelヘッダー編集不可能poi

私はまず、sheet.protectSheet("password")を実行し、最終的にはシート全体を編集不可能にして、編集可能なセルすべてをループし、cellStyleをcellStyle.setLocked(false)として設定すると言うさまざまな解決策を得ました。

私のケースでは、Excelにはヘッダーだけが含まれているため、残りの行がユーザーによって埋め尽くされるため、シート全体を編集不可能にすることはできません。ヘッダーは編集できません。どうすればこれを達成できますか? XSSF、以下のものを使用して

+0

「私はちょうどヘッダーは、ユーザーが編集できないようにしたい。」:その後、あなたはどのように使用してその要件を満たすでしょう ' ExcelのGUIですか?なぜなら、 'apache poi'は' Excel'自体ができないことをすることができないからです。 –

+0

@Fabien編集のおかげで:) –

答えて

0

を達成することができ:

は、すべての列のデフォルトスタイルとしてCellStylesetLocked偽を設定します。これは、そのスタイルを設定した最小列1と最大列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(); 
} 
} 
+0

大変ありがとうございました。それは私のために働いた。 –

関連する問題