- Apache POI Tutorial
- Apache POI - Home
- Apache POI - Overview
- Apache POI - Java Excel APIs
- Apache POI - Environment
- Apache POI - Core Classes
- Apache POI - Workbooks
- Apache POI - Spreadsheets
- Apache POI - Cells
- Apache POI - Fonts
- Apache POI - Formula
- Apache POI - Hyperlink
- Apache POI - Print Area
- Apache POI - Database
- Apache POI Resources
- Apache POI - Questions & Answers
- Apache POI - Quick Guide
- Apache POI - Useful Resources
- Apache POI - Discussion
Apache POI – 打印区域
本章介绍如何在电子表格上设置打印区域。Excel 电子表格中通常的打印区域是从左上到右下。打印区域可根据您的要求定制。这意味着您可以打印整个电子表格中特定范围的单元格、自定义纸张尺寸、在打开网格线的情况下打印内容等。
以下代码用于在电子表格上设置打印区域。
import java.io.File; import java.io.FileOutputStream; import org.apache.poi.xssf.usermodel.XSSFPrintSetup; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class PrintArea { public static void main(String[] args)throws Exception { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet spreadsheet = workbook.createSheet("Print Area"); //set print area with indexes workbook.setPrintArea( 0, //sheet index 0, //start column 5, //end column 0, //start row 5 //end row ); //set paper size spreadsheet.getPrintSetup().setPaperSize(XSSFPrintSetup.A4_PAPERSIZE); //set display grid lines or not spreadsheet.setDisplayGridlines(true); //set print grid lines or not spreadsheet.setPrintGridlines(true); FileOutputStream out = new FileOutputStream(new File("printarea.xlsx")); workbook.write(out); out.close(); System.out.println("printarea.xlsx written successfully"); } }
让我们将上面的代码保存为PrintArea.java。从命令提示符处编译并执行它,如下所示。
$javac PrintArea.java $java PrintArea
它将在当前目录中生成一个名为printarea.xlsx的文件,并在命令提示符下显示以下输出。
printarea.xlsx written successfully
在上面的代码中,我们没有添加任何单元格值。因此printarea.xlsx是一个空白文件。但您可以在下图中观察到,打印预览显示带有网格线的打印区域。