Apache POI是否可以提取工作表的唯一可重命名的“ CodeName”值?

时间:2019-01-17 12:13:59

标签: excel apache-poi

Excel工作表显然具有一个名为“ CodeName”的属性,该属性是唯一的,即使工作表已重命名也保持不变:https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.codename

是否可以使用Apache POI获取“ CodeName”的值?

1 个答案:

答案 0 :(得分:2)

至少对于Office Open XML(*.xlsx),工作表的代码名称以/xl/worksheets/sheet[n].xml的形式存储在<sheetPr codeName="TheCodeName"/>中。因此至少使用XSSFSheet可以使用底层基础对象org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet来实现。

示例:

enter image description here

代码:

import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;

class ExcelGetSheetByCodeName {

 private static Sheet getSheetByCodeName(Workbook workbook, String codeName) {
  for (Sheet sheet : workbook) {
   if (sheet instanceof XSSFSheet) {
    XSSFSheet xssfSheet = (XSSFSheet)sheet;
System.out.println(xssfSheet.getCTWorksheet().getSheetPr().getCodeName());
    if (codeName.equals(xssfSheet.getCTWorksheet().getSheetPr().getCodeName())) {
     return xssfSheet;
    }
   } else {
    System.out.println("only XSSF implemented yet");
   }
  }
  return null;
 }

 public static void main(String[] args) throws Exception {

  Workbook workbook = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx")); 
  Sheet sheet = getSheetByCodeName(workbook, "TheCodeName");

System.out.println("found sheet: " + sheet);

 }
}

结果:

axel@arichter:~/Dokumente/JAVA/poi/poi-4.0.1$ java -cp .:./*:./lib/*:./ooxml-lib/* ExcelGetSheetByCodeName 
Foo
TheCodeName
found sheet: Name: /xl/worksheets/sheet2.xml - Content Type: application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml