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.

    1. import java.io.File;
    2. import java.io.FileOutputStream;
    3.  
    4. import org.apache.poi.xssf.usermodel.XSSFPrintSetup;
    5. import org.apache.poi.xssf.usermodel.XSSFSheet;
    6. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    7.  
    8. public class PrintArea {
    9. public static void main(String[] args)throws Exception {
    10. XSSFWorkbook workbook = new XSSFWorkbook();
    11. XSSFSheet spreadsheet = workbook.createSheet("Print Area");
    12.  
    13. //set print area with indexes
    14. workbook.setPrintArea(
    15. 0, //sheet index
    16. 0, //start column
    17. 5, //end column
    18. 0, //start row
    19. 5 //end row
    20. );
    21.  
    22. //set paper size
    23. spreadsheet.getPrintSetup().setPaperSize(XSSFPrintSetup.A4_PAPERSIZE);
    24.  
    25. //set display grid lines or not
    26. spreadsheet.setDisplayGridlines(true);
    27.  
    28. //set print grid lines or not
    29. spreadsheet.setPrintGridlines(true);
    30.  
    31. FileOutputStream out = new FileOutputStream(new File("printarea.xlsx"));
    32. workbook.write(out);
    33. out.close();
    34. System.out.println("printarea.xlsx written successfully");
    35. }
    36. }

    Let us save the above code as PrintArea.java. Compile and execute it from the command prompt as follows.

    1. $javac PrintArea.java
    2. $java PrintArea

    It will generate a file named printarea.xlsx in your current directory and display the following output on the command prompt.

    1. printarea.xlsx written successfully

    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.

    printarea.jpeg