我想使用poi使我的excel的標題行不可編輯。Excel頭文件不可編輯poi
我在互聯網上得到了各種解決方案,首先做sheet.protectSheet("password")
,最終使整張紙不可編輯,然後遍歷所有可編輯的單元格,並將它們的cellStyle設置爲cellStyle.setLocked(false)
。
在我的情況下,由於excel只是包含標題,其餘的行將由用戶填寫,我不能使整個表不可編輯,我只是希望用戶無法編輯標題。我怎樣才能做到這一點?
我想使用poi使我的excel的標題行不可編輯。Excel頭文件不可編輯poi
我在互聯網上得到了各種解決方案,首先做sheet.protectSheet("password")
,最終使整張紙不可編輯,然後遍歷所有可編輯的單元格,並將它們的cellStyle設置爲cellStyle.setLocked(false)
。
在我的情況下,由於excel只是包含標題,其餘的行將由用戶填寫,我不能使整個表不可編輯,我只是希望用戶無法編輯標題。我怎樣才能做到這一點?
使用XSSF
以下可以實現:
設置一個CellStyle
有setLocked
假作爲所有列的默認樣式。這可以通過設置具有設置該樣式的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
元素並在那裏設置CustomFormat
和S
(樣式)。
結果:所有細胞被解鎖,除了第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();
}
}
非常感謝您的幫助。它爲我工作。 –
「我只想頭是由用戶編輯。」:那怎麼會使用你滿足這一要求' Excel的GUI?因爲'apache poi'不能做一些'Excel'本身無法做到的事情。 –
@Fabien感謝您的編輯:) –