本章介紹了如何在電子表格中設(shè)置打印區(qū)域。通常打印區(qū)域從左上角到Excel電子表格右下角。打印區(qū)域可根據(jù)要求進(jìn)行定制。它意味著可以從整個(gè)電子表格打印單元的特定范圍,自定義的紙張大小,用網(wǎng)格線打印的內(nèi)容接通等
以下代碼是用來在電子表格中設(shè)置打印區(qū)域。
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。編譯并從命令提示符執(zhí)行它如下。
$javac PrintArea.java $java PrintArea
它會(huì)生成一個(gè)名為printarea.xlsx在當(dāng)前目錄下的文件,并顯示在命令提示符處輸出以下。
printarea.xlsx written successfully
在上面的代碼中,我們還沒有添加任何單元格值。因此printarea.xlsx是一個(gè)空白文件。但是可以在下圖的打印預(yù)覽顯示網(wǎng)格線打印區(qū)域查看。