在apache poi中,我们可以使用sheet.setZoom(120)设置缩放值。但是当我们复制/克隆同一张纸时,我们将如何获得缩放值。我找不到方法 srcSheet.getZoom();。此方法有什么替代方法?.
如果
apache poi
缺少方法我们该怎么办?我们可以看看它是如何编写类似方法的。例如,XSSFSheet..setZoom 除了设置默认 CTSheetView的
zoomScale
之外什么也不做。因此,如果我们要获得默认的工作表视图,我们可以做相反的事情并获得 zoomScale
。
示例:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetView;
import java.lang.reflect.Method;
public class ExcelXSSFSheetZoom {
static long getZoom(XSSFSheet sheet) throws Exception {
Method getDefaultSheetView = XSSFSheet.class.getDeclaredMethod("getDefaultSheetView");
getDefaultSheetView.setAccessible(true);
CTSheetView sheetview = (CTSheetView)getDefaultSheetView.invoke(sheet);
return sheetview.getZoomScale();
}
public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
sheet.setZoom(120);
System.out.println(getZoom((XSSFSheet)sheet));
wb.write(new FileOutputStream("ExcelXSSFSheetZoom.xlsx"));
wb.close();
}
}
当前的 Apache poi 版本没有零参数方法
private CTSheetView getDefaultSheetView()
,而只有 private CTSheetView getDefaultSheetView(final boolean create)
。因此当前的 Apache POI 版本必须是相同的:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetView;
import java.lang.reflect.Method;
public class ExcelXSSFSheetZoom {
static long getZoom(XSSFSheet sheet) throws Exception {
Method getDefaultSheetView = XSSFSheet.class.getDeclaredMethod("getDefaultSheetView", boolean.class);
getDefaultSheetView.setAccessible(true);
CTSheetView sheetview = (CTSheetView)getDefaultSheetView.invoke(sheet, true);
return sheetview.getZoomScale();
}
public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
sheet.setZoom(120);
System.out.println(getZoom((XSSFSheet)sheet));
FileOutputStream out = new FileOutputStream("ExcelXSSFSheetZoom.xlsx");
wb.write(out);
out.close();
wb.close();
}
}