我正在使用apache创建一个.xls excel文件。默认情况下,我需要设置分页视图。但我确实看了一个关于.xlsx文件的相关问题。我没有找到任何“如何设置分页查看模式”来使用ApachePOI的HSSF
发布于 2021-12-16 13:26:14
*.xls的二进制*.xls文件系统和*.xlsx的Office Open XML文件系统是两种完全不同的文件系统。你不能把它们混在一起。在apache poi HSSF ist中,其中一个是XSSF,另一个是XSSF。apache poi的高级类尝试为两个文件系统提供方法。这是使用SS中的接口完成的。但是在高级类之外,需要严格区分这两个文件系统。
设置工作表的分页预览到目前为止还没有由高级类提供。所以我们需要低水平的课程。对于XSSF,这是org.openxmlformats.schemas.spreadsheetml.x2006.main.*类,它是XSSF内部的XML表示。但是对于HSSF,这是org.apache.poi.hssf.record.*类,它们是HSSF内部的二进制表示。
对于两个文件系统,可以这样设置工作表的分页预览:
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.model.InternalSheet;
import org.apache.poi.hssf.record.WindowTwoRecord;
public class ExcelPageBreakPreview {
public static void main(String[] args) throws Exception {
//Workbook workbook = WorkbookFactory.create(new FileInputStream("./ExcelTemplate.xlsx")); String filePath = "./ExcelInPageBreakPreview.xlsx";
Workbook workbook = WorkbookFactory.create(new FileInputStream("./ExcelTemplate.xls")); String filePath = "./ExcelInPageBreakPreview.xls";
Sheet sheet = workbook.getSheetAt(0);
//set sheet in PageBreakPreview
if (sheet instanceof XSSFSheet) {
XSSFSheet xssfSheet= (XSSFSheet)sheet;
xssfSheet.lockSelectLockedCells(true);
xssfSheet.getCTWorksheet().getSheetViews().getSheetViewArray(0).setView(org.openxmlformats.schemas.spreadsheetml.x2006.main.STSheetViewType.PAGE_BREAK_PREVIEW);
} else if (sheet instanceof HSSFSheet) {
HSSFSheet hssfSheet= (HSSFSheet)sheet;
InternalSheet internalSheet = hssfSheet.getSheet();
WindowTwoRecord record = internalSheet.getWindowTwo();
record.setSavedInPageBreakPreview(true);
}
FileOutputStream fileOut = new FileOutputStream(filePath);
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
}以前的apache poi版本可能没有InternalSheet HSSFSheet.getSheet公共的。然后,需要使用反射来获取InternalSheet
//InternalSheet internalSheet = hssfSheet.getSheet();
java.lang.reflect.Field _sheet = HSSFSheet.class.getDeclaredField("_sheet");
_sheet.setAccessible(true);
InternalSheet internalSheet = (InternalSheet)_sheet.get(hssfSheet); https://stackoverflow.com/questions/70373491
复制相似问题