使用POI操作Excel时如何隐藏、删除Excel中指定的Sheet呢?在POI的API中的HSSFWorkbook类提供了相关的方法,
(1)隐藏Sheet:
setSheetHidden(int sheetIx, boolean hidden);
sheetIx
– the sheet index (0-based)
hidden
– True to mark the sheet as hidden, false otherwise
setSheetHidden(int sheetIx, int hidden);
-
sheetIx
– the sheet index (0-based) -
hidden
– one of the followingWorkbook
constants:Workbook.SHEET_STATE_VISIBLE
,Workbook.SHEET_STATE_HIDDEN
, orWorkbook.SHEET_STATE_VERY_HIDDEN
. - 0 – visible / 1 – hidden / 2 – very hidden.
(2)删除Sheet:
removeSheetAt(int sheetId)
index
– of the sheet (0-based)
Java代码:
/**
* 隐藏指定的Sheet
* @param targetFile 目标文件
* @param sheetName Sheet名称
*/
public void hiddenSheet(String targetFile,String sheetName) {
try {
FileInputStream fis = new FileInputStream(targetFile);
HSSFWorkbook wb = new HSSFWorkbook(fis);
//隐藏Sheet
wb.setSheetHidden(wb.getSheetIndex(sheetName), 1);
this.fileWrite(targetFile, wb);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除指定的Sheet
* @param targetFile 目标文件
* @param sheetName Sheet名称
*/
public void deleteSheet(String targetFile,String sheetName) {
try {
FileInputStream fis = new FileInputStream(targetFile);
HSSFWorkbook wb = new HSSFWorkbook(fis);
//删除Sheet
wb.removeSheetAt(wb.getSheetIndex(sheetName));
this.fileWrite(targetFile, wb);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 写隐藏/删除后的Excel文件
* @param targetFile 目标文件
* @param wb Excel对象
* @throws Exception
*/
public void fileWrite(String targetFile,HSSFWorkbook wb) throws Exception{
FileOutputStream fileOut = new FileOutputStream(targetFile);
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
调用测试:
public static void main(String[] args) {
ExcelWrite ew = new ExcelWrite();
ew.deleteSheet("d:/test.xls", "template1");
ew.hiddenSheet("d:/test.xls", "template2");
}
隐藏、删除Sheet之后必须将HSSFWorkbook对象从新写成文件(覆盖原来的文件),这样所做的修改才起作用!