[]
        
(Showing Draft Content)

配置分页符

GcExcel Java 允许用户使用 IWorksheet 接口的 getHPageBreaks 方法和  getVPageBreaks 方法配置垂直和水平分页符。

还可以通过使用 IWorksheet 接口的 getFixedPageBreaks 和 setFixedPageBreaks 方法来确定是调整水平和垂直分页符还是保持固定(在对行和列执行插入和删除操作时)。

当用户需要将不同的报表从Excel打印到PDF文件时,此功能尤其有用。通过选择是调整分页符还是固定分页符的选项,用户可以指定在电子表格中插入或删除任何行和列时,每个节是显示在单独的页上还是从新页开始。

如果 setFixedPageBreaks 方法设置为false(这是默认行为),则:

  • 在工作表中插入或删除行和列时,会调整水平和垂直分页符。

  • 分页符的行或列索引根据插入和删除的行或列根据以下条件增减:

    • 如果在分页符之后存在插入或删除的行或列,则分页符的行或列索引保持不变。

    • 如果删除的行或列出现在分页符之前,则分页符的行或列索引将相应减少。

    • 如果删除的行或列包含分页符,则将删除分页符。

如果 setFixedPageBreaks 方法设置为true,则即使在插入或删除行或列之后,分页符的行或列索引也不会更改。此外,水平和垂直分页符被认为是“fixed”,在这种情况下不能调整分页符。

要为自定义打印配置分页符,请参阅以下示例代码。

// Initialize workbook
Workbook workbook = new Workbook();
        
// Fetch default worksheet
IWorksheet worksheet = workbook.getWorksheets().get(0);

Object data = new Object[][] { 
{ "Name", "City", "Birthday", "Sex", "Weight", "Height", "Age" },
{ "Bob", "NewYork", new GregorianCalendar(1968, 6, 8), "male", 80, 180, 56 },
{ "Betty", "NewYork", new GregorianCalendar(1972, 7, 3), "female", 72, 168, 45 },
{ "Gary", "NewYork", new GregorianCalendar(1964, 3, 2), "male", 71, 179, 50 },
{ "Hunk", "Washington", new GregorianCalendar(1972, 8, 8), "male", 80, 171, 59 },
{ "Cherry", "Washington", new GregorianCalendar(1986, 2, 2), "female", 58, 161, 34 },
{ "Coco", "Virginia", new GregorianCalendar(1982, 12, 12), "female", 58, 181, 45 },
{ "Lance", "Chicago", new GregorianCalendar(1962, 3, 12), "female", 49, 160, 57 },
{ "Eva", "Washington", new GregorianCalendar(1993, 2, 5), "female", 71, 180, 81 } };

// Set data
worksheet.getRange("A1:G9").setValue(data);

// Add a horizontal page break before the fourth row
IHPageBreak hPageBreak = worksheet.getHPageBreaks().add(worksheet.getRange("F4"));
        
// Add a vertical page break before the third column
IVPageBreak vPageBreak = worksheet.getVPageBreaks().add(worksheet.getRange("F3"));

// Saving workbook to xlsx
workbook.save("7-PageBreaks.xlsx", SaveFileFormat.Xlsx);

/* Delete rows and columns before the page breaks, the page breaks will be
   adjusted */
worksheet.getRange("1:2").delete(); // hPageBreak is before the 4th row
worksheet.getRange("B:C").delete(); // vPageBreak is before the 4th column

/* Set the page breaks are fixed, it will not be adjusted when inserting/
   deleting rows/ columns */
worksheet.setFixedPageBreaks(true);

// Saving workbook to xlsx
workbook.save("PageBreaks1.xlsx", SaveFileFormat.Xlsx);

/* Delete rows and columns after the page breaks, the page breaks will not be
   adjusted */
worksheet.getRange("1:2").delete(); // hPageBreak is still before the 4th row
worksheet.getRange("B:C").delete(); // vPageBreak is still before the 4th column

// Inserting rows after deleting row and column ranges
worksheet.getRange("A3:A5").getEntireRow().insert();

// Saving workbook to xlsx
workbook.save("PageBreaks2.xlsx", SaveFileFormat.Xlsx);