Apache Poi 简明教程
Apache POI – Print Area
这一章解释了如何在电子表格上设置打印区域。在 Excel 电子表格中,常见的打印区域是从左上角打印到右下角。可以根据你的要求定制打印区域。这意味着你可以从整个电子表格打印特定范围的单元格,自定义纸张大小,在网格线打开的情况下打印内容,等等。
This chapter explains how to set the print area on a spreadsheet. The usual print area is from left top to right bottom on Excel spreadsheets. Print area can be customized according to your requirement. It means you can print a particular range of cells from the whole spreadsheet, customize the paper size, print the contents with the grid lines turned on, etc.
以下代码用于在电子表格上设置打印区域。
The following code is used to set up the print area on a spreadsheet.
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 。从命令提示符中编译并执行它,如下所示。
Let us save the above code as PrintArea.java. Compile and execute it from the command prompt as follows.
$javac PrintArea.java
$java PrintArea
它将在你的当前目录中生成一个名为 printarea.xlsx 的文件,然后在命令提示符上显示以下输出。
It will generate a file named printarea.xlsx in your current directory and display the following output on the command prompt.
printarea.xlsx written successfully
在以上代码中,我们没有添加任何单元格值。因此 printarea.xlsx 是一个空白文件。但你可以观察到,在下图中,打印预览显示了带有网格线的打印区域。
In the above code, we have not added any cell values. Hence printarea.xlsx is a blank file. But you can observe in the following figure that the print preview shows the print area with grid lines.
